具有列成2D向量的C ++文本文件 [英] C++ text file with columns into 2D vector
问题描述
我有一个包含值的文本文件,我想将它们放入2D向量中.
I have a text file that has values and I want to put them into a 2D vector.
我可以用数组来做,但是我不知道如何用向量来做.
I can do it with arrays but I don't know how to do it with vectors.
向量大小应类似于我事先不知道的vector2D [nColumns] [nLines].在文本文件中,最多可以有多少列,但没有行数.从一个.txt文件到另一个.txt文件,列数可以不同.
The vector size should be like vector2D[nColumns][nLines] that I don't know in advance. At the most I can have in the text file the number of columns, but not the number of lines. The number of columns could be different, from one .txt file to another.
.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
使用数组,我是这样的:
with arrays I do it like this:
//------ 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;
}
}
推荐答案
我的建议:
const int nCol = countCols; // read from file
std::vector<std::vector<float>> values; // your entire data-set of values
std::vector<float> line(nCol, -1.0); // create one line of nCol size and fill with -1
// reads file to end of *file*, not line
bool done = false;
while (!done)
{
for (int i = 0; !done && i < nCol; i++)
{
done = !(inFile >> line[i]);
}
values.push_back(line);
}
现在您的数据集具有:
values.size() // number of lines
,并且也可以使用数组符号(除了使用迭代器之外):
and can be adressed with array notation also (besides using iterators):
float v = values[i][j];
注意:该代码未考虑到最后一行可能小于nCol数据值的事实,因此行向量的末尾在文件末尾将包含错误的值.在将其推入值之前,您可能需要添加代码以清除行向量的结尾(当完成变为假时).
Note: this code does not take into account the fact that the last line may have less that nCol data values, and so the end of the line vector will contain wrong values at end of file. You may want to add code to clear the end of the line vector when done becomes false, before you push it into values.
这篇关于具有列成2D向量的C ++文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!