如何从一行一行的文件到多个向量(vectros的向量)有效地读取数据(相同类型)?

时间:2019-01-07 12:10:07

标签: c++ c++11

我的文件超过100个。元素(相同类型的数据,例如int)。每个元素都在其他行中。 文件结构:
整数
整数
...
int

我必须将此数据读取到2D数组(5个向量的向量)中:
-第一行到第一个向量
-第二行到第二矢量
....
-第五行到第五个向量
-第一个向量的第六行...

从文件的开头到结尾。

std::vector<std::vector<int>> my_v;
std::ifstream in( "data.txt" );
std::string record;

while ( std::getline( in, record ) )
{
    std::istringstream is( record );
    std::vector<int> row( ( std::istream_iterator<int>( is ) ),
                             std::istream_iterator<int>() );
    my_v.push_back( row );
}

for ( const auto &row : my_v )
{
    for ( double x : row ) std::cout << x << ' ';
    std::cout << std::endl;
}        

现在我正在将数据读取到一个向量。如何解决?

1 个答案:

答案 0 :(得分:0)

该示例代码似乎适用于某种不同的格式。我猜您实际上不是亲自编写此代码,也不真正理解它。根据描述和一些常识,我认为您正在寻找的是

std::vector<std::vector<int>> my_v(5); // five vectors
std::ifstream in("data.txt");
int value, i = 0;

// read a value
while (in >> value)
{
    // add to the 'i'th vector
    my_v[i].push_back(value);
    // update i
    if (++i == 5)
        i = 0;
}

// print results
for ( const auto &row : my_v )
{
    for ( int x : row ) std::cout << x << ' ';
    std::cout << std::endl;
}