C++文本文件,将列转换为二维矢量

C++ text file with columns into 2D vector

本文关键字:二维 文件 文本 转换 C++      更新时间:2023-10-16

我有一个包含值的文本文件,我想将它们放入2D向量中。

我可以用数组来做,但我不知道如何用向量来做。

向量大小应该像vector2D[nColumns][nLines],我事先不知道。文本文件中最多只能有列数,但不能有行数。不同的.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]; 

使用

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]

注意:你也可以用std::array代替vector,这显然是切片面包之后最好的东西。

我的建议:

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

并且还可以使用数组表示法(除了使用迭代器之外):

float v = values[i][j];

注意:此代码没有考虑到最后一行的数据值可能小于nCol这一事实,因此行向量的末尾将在文件末尾包含错误的值。当done变为false时,您可能需要添加代码来清除行向量的末尾,然后再将其推送到值中。