使用指针为文件C++中的数字动态分配存储

using a pointer to dynamically allocate storage for the numbers from file C++

本文关键字:数字 动态分配 存储 C++ 指针 文件      更新时间:2023-10-16

我想为文件中的数字分配存储空间,而不是将它们存储在列表中,然后找到数字的平均值。我已经为下面的列表做了这件事,但我很难理解为指针做这件事的概念。感谢您的帮助。

您需要克服的主要问题是确定分配多少内存来容纳所有双打。有几种方法可以做到这一点:

"最简单"的方法是做一些天真的事情,比如完全读取文件一次以获得双倍数,然后再次读取文件以将值实际存储在数组中:

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个double。为您的阵列分配新的(类似于上面的例子),然后继续将文件的其余部分读取到其中

另一种选择是像std::vector那样,首先在数组中为1个元素分配足够的内存。如果需要添加另一个元素,而数组已满,请用两倍的内存重新分配数组,并将旧元素复制/移动到其中。根据需要重复此操作。

使用C++容器,您不必担心内存分配问题。列表元素存储在HEAP上。这基本上就是您试图通过使用指针来实现的。

请参阅列表和列表元素,存储在哪里?,当分配向量时,它们是使用堆上的内存还是堆栈上的内存?了解更多信息。

如果你仍然想使用指针,我建议你使用共享指针http://en.cppreference.com/w/cpp/memory/shared_ptr,或另一个std智能指针。