我有一个包含值的文本文件,我想将它们放入二维向量中。
我可以用数组来做到这一点,但我不知道如何用向量来做到这一点。
矢量大小应该像我事先不知道的 vector2D[nColumns][nLines] 。我最多可以在文本文件中包含列数,但不能包含行数。
一个 .txt 文件与另一个 .txt 文件的列数可能不同。
.txt 示例:
189.53 -1.6700 58.550 33.780 58.867
190.13 -3.4700 56.970 42.190 75.546
190.73 -1.3000 62.360 34.640 56.456
191.33 -1.7600 54.770 35.250 65.470
191.93 -8.7500 58.410 33.900 63.505
对于数组我这样做:
//------ Declares Array for values ------//
const int nCol = countCols; // read from file
float values[nCol][nLin];
// Fill Array with '-1'
for (int c = 0; c < nCol; c++) {
for (int l = 0; l < nLin; l++) {
values[c][l] = -1;
}
}
// reads file to end of *file*, not line
while (!inFile.eof()) {
for (int y = 0; y < nLin; y++) {
for (int i = 0; i < nCol; i++) {
inFile >> values[i][y];
}
i = 0;
}
}
而不是使用
float values[nCol][nLin];
use
std::vector<std::vector<float>> v;
你必须#include<vector>
为了这。
现在您无需担心尺寸。
添加元素就像这样简单
std::vector<float> f; f.push_back(7.5); v.push_back(f);
也不要使用.eof()
在流上,因为它直到到达末尾才设置它,因此它将尝试读取文件的末尾。
while(!inFile.eof())
应该
while (inFile >> values[i][y]) // returns true as long as it reads in data to values[x][y]
注意:而不是vector
,您还可以使用std::array
,这显然是切片面包之后最好的东西。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)