使用指针为文件 C++ 中的数字动态分配存储空间
using a pointer to dynamically allocate storage for the numbers from file C++
我想为文件中的数字分配存储空间,而不是将它们存储在列表中,然后求出数字的平均值。我已经为下面的列表做了这个,但我正在为一个指针做这个的概念而苦苦挣扎。感谢您的帮助。
使用 C++ 容器,您无需担心内存分配问题。列表元素存储在 HEAP 中。这基本上就是您试图通过使用指针实现的目标。
有关详细信息,请参阅 List and list elements, where are stored?, When vectors are allocated, do they use memory on the heap or the stack?。
如果您仍想使用指针,我建议您使用共享指针 http://en.cppreference.com/w/cpp/memory/shared_ptr,或其他标准智能指针。
您需要克服的主要问题是确定要分配多少内存来容纳所有双打。有几种方法可以做到这一点:
"easiest" 方法是做一些天真的事情,比如完全读取文件一次以获得双精度数,然后再次读取文件以实际将值存储在数组中:
std::ifstream in("numbers.txt");
unsigned int numElements = 0;
// Read the file once to determine how many elements it contains
double discard;
while (in >> discard) {
numElements++;
}
// Go back to the beginning of file
in.clear() ;
in.seekg(0, std::ios::beg);
// Allocate array and read file contents into it
double* data = new double[numElements];
for ( int i = 0; i < numElements && is >> data[i]; i++ );
// Calculate the sum and average
double sum = 0;
for ( int i = 0; i < numElements; i++ ) {
sum += data[i];
}
double average = sum / numElements;
// Free the dynanmically allocated memory
delete[] data;
读取一个文件两次是非常低效的;还有其他方法可以预先获取大小。例如,您可以在输入文件中约定将元素数作为数据之前的第一个值包含在内:
[infile.txt]
5 1.0 2.0 3.0 4.0 5.0
现在您可以从文件中读取第一个值,并且您会知道该文件的其余部分包含 5 个双精度值。使用 new 分配数组(类似于上面的示例),然后继续将文件的其余部分读入其中。
另一种选择是做 std::vector
做的事情,首先在数组中为 1 个元素分配足够的内存。如果你需要添加另一个元素,而数组已经满了,重新分配你的数组两倍的内存和 copy/move 你的旧元素。根据需要重复。
我想为文件中的数字分配存储空间,而不是将它们存储在列表中,然后求出数字的平均值。我已经为下面的列表做了这个,但我正在为一个指针做这个的概念而苦苦挣扎。感谢您的帮助。
使用 C++ 容器,您无需担心内存分配问题。列表元素存储在 HEAP 中。这基本上就是您试图通过使用指针实现的目标。
有关详细信息,请参阅 List and list elements, where are stored?, When vectors are allocated, do they use memory on the heap or the stack?。
如果您仍想使用指针,我建议您使用共享指针 http://en.cppreference.com/w/cpp/memory/shared_ptr,或其他标准智能指针。
您需要克服的主要问题是确定要分配多少内存来容纳所有双打。有几种方法可以做到这一点:
"easiest" 方法是做一些天真的事情,比如完全读取文件一次以获得双精度数,然后再次读取文件以实际将值存储在数组中:
std::ifstream in("numbers.txt");
unsigned int numElements = 0;
// Read the file once to determine how many elements it contains
double discard;
while (in >> discard) {
numElements++;
}
// Go back to the beginning of file
in.clear() ;
in.seekg(0, std::ios::beg);
// Allocate array and read file contents into it
double* data = new double[numElements];
for ( int i = 0; i < numElements && is >> data[i]; i++ );
// Calculate the sum and average
double sum = 0;
for ( int i = 0; i < numElements; i++ ) {
sum += data[i];
}
double average = sum / numElements;
// Free the dynanmically allocated memory
delete[] data;
读取一个文件两次是非常低效的;还有其他方法可以预先获取大小。例如,您可以在输入文件中约定将元素数作为数据之前的第一个值包含在内:
[infile.txt]
5 1.0 2.0 3.0 4.0 5.0
现在您可以从文件中读取第一个值,并且您会知道该文件的其余部分包含 5 个双精度值。使用 new 分配数组(类似于上面的示例),然后继续将文件的其余部分读入其中。
另一种选择是做 std::vector
做的事情,首先在数组中为 1 个元素分配足够的内存。如果你需要添加另一个元素,而数组已经满了,重新分配你的数组两倍的内存和 copy/move 你的旧元素。根据需要重复。