我试图用C++编写代码,从文件读取,一系列点,将其存储在动态数组中,然后打印回来.
这是我给出的规范:
"我们希望利用我们可以使用动态内存的事实,因此我们不是根据我们的估计在开始时分配足够大的内存量,而是实现以下算法:
最初,分配的内存非常少.
在循环的每次迭代中(从文件读取并存储到动态数组中),我们跟踪:
当由于新插入而导致元素数量大于数组最大大小时,内存重新分配需要按如下方式进行:
从我下面的代码中,我认为其他一切都很好但是最后一个要求,即在数组末尾添加新项目.
当数组Max_Size超过文件的元素数时,代码工作正常,但是当我尝试扩展num_elements时,结果是文件中的额外数字只保存为零
.
另外,分配还不允许使用向量.对不起,我忘了提这个,我是stackoverflow的新手,有点编程.
请帮忙
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
struct point {
double x;
double y;
};
int main () {
ifstream inputfile;
inputfile.open("datainput.txt");
if(!inputfile.is_open()){
cout << "could not open file" << endl;
exit(EXIT_FAILURE);
}
//initially very little memory is allocated
int Max_Size = 10;
int num_elements = 0;
point *pp = new point[Max_Size];
//read from file and store in dynamic array …Run Code Online (Sandbox Code Playgroud) c++ arrays algorithm memory-management dynamic-memory-allocation