【发布时间】:2018-10-17 14:32:09
【问题描述】:
我有以下包含值的文件 input.txt:
0 0
0 1
0 2
0 3
1 1
1 4
2 1
2 4
2 3
我想将这些值插入两个数组。我希望他们最终看起来像这样。
0 0 1 2 3
1 1 4
2 1 4 3
第一个数组将包含 id,第二个数组将包含元素。我已经设法使用以下方法为这两个数组动态分配内存:
int n,m,i=0,tempNum,lines;
int NumberOfIds=0;
ifstream read("input2.txt");
while(read>>n>>m){
if (i==0){
tempNum=n;
}
if (tempNum != n){
NumberOfIds++;
}
tempNum = n;
i++;
}
lines=i-1;
//printf("%d", j);
int** idElements = new int*[NumberOfIds];
int* ids = new int[NumberOfIds];
int* numberOfIdElements = new int[NumberOfIds];
// Rewinds file
read.clear();
read.seekg(0, ios::beg);
int counter = 0;
NumberOfIds=0;
while(read>>n>>m){
if (tempNum != n){
numberOfIdElements[NumberOfIds] = counter;
NumberOfIds++;
counter = 0;
}
tempNum = n;
counter++;
i++;
}
for(int k = 0; k < NumberOfIds; ++k)
idElements[k] = new int[numberOfIdElements[k]];
现在我被困在如何插入数据上。任何帮助将不胜感激。
【问题讨论】:
标签: c++ arrays file input dynamic-memory-allocation