将txt文件值插入到多维向量中

时间:2015-04-03 23:45:56

标签: c++ multidimensional-array vector

我需要一些帮助,将一系列值插入到矢量中。 例如,我的.txt文件看起来像这样;

0
0
35
0
2
0
35
0
0
0
2
0
etc.

我需要将这些值插入到2D矢量中。即。如果表格是10x5,它看起来像;

0 0 35 0  2
0 2 0  35 0
0 0 2  0  etc.

我想使用这样的东西:

vector<vector<int>> Pix;

vector<int> tmp_col;
int i;
int j;

for (i=0; i<largeur; i++) {
    for (j=0; j<hauteur; j++) {

    }
}

但我不知道如何使用push.back函数或get.line(我对编程很新)

感谢您的帮助:)))

1 个答案:

答案 0 :(得分:0)

如果您知道文本文件中的尺寸和值始终用空格分隔,其中包括换行符,则可以执行以下操作:

vector<vector<int>> Pix(height, vector<int>(width));

for (auto& y : Pix)
{
    for (auto& x : y)
    {
        if (! (mystream >> x))
        {
            // failure to parse
        }
    }
}

请注意,矢量应编入索引为Pix[y][x]

相关问题