使用指针为文件C++中的数字动态分配存储
using a pointer to dynamically allocate storage for the numbers from file C++
我想为文件中的数字分配存储空间,而不是将它们存储在列表中,然后找到数字的平均值。我已经为下面的列表做了这件事,但我很难理解为指针做这件事的概念。感谢您的帮助。
您需要克服的主要问题是确定分配多少内存来容纳所有双打。有几种方法可以做到这一点:
"最简单"的方法是做一些天真的事情,比如完全读取文件一次以获得双倍数,然后再次读取文件以将值实际存储在数组中:
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智能指针。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 使用递归模板动态分配的多维数组
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 访问动态分配列表中的元素
- 为什么 std::equal_to会导致动态分配?
- 调用析构函数以释放动态分配的内存
- 动态分配Q_Property变量
- 在 C++ 中搜索动态分配的数组中的出现次数
- 动态分配的聊天数组打印缺失的数据和空
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 使用动态分配将 char* 复制到另一个字符**
- 使用指针在存在特征库的情况下动态分配 c++ 中的矩阵
- 二维阵列的动态分配
- 合并排序C++帮助 为合并的数字动态分配临时数组
- 在打印出动态分配的数组中的前两个数字时遇到问题,其他数字工作正常
- 使用指针为文件C++中的数字动态分配存储
- 在读取文件时,在增加数组大小的同时,将浮点数字读取到动态分配的中