代码之家  ›  专栏  ›  技术社区  ›  mahmood

读取矩阵中可变大小的列

  •  0
  • mahmood  · 技术社区  · 12 年前

    我有一个文件,它在不同的行中包含不同的列。例如

    10 20 30 60 
    60 20 90 100 40 80
    20 50 60 30 90
    ....
    

    我想读每一行的最后三个数字。因此输出将是

    20 30 60 
    100 40 80
    60 30 90
    

    由于每行大小不一,我不能使用以下结构

    结构1:

    std::ifstream fin ("data.txt");
    while (fin >> a >> b >> c) {...}
    

    结构2:

    string line;
    stringstream ss;
    getline(fin, line);
    ss << line;
    int x, y, z;
    ss >> x >> y >> z >> line;
    

    那我该怎么办?

    1 回复  |  直到 12 年前
        1
  •  1
  •   Zac Howland    12 年前

    把它们读成 std::vector 除了最后三个项目外,其他项目都去掉。

    std::string line;
    while (getline(fin, line))
    {
        std::vector<int> vLine;
        istringstream iss(line);
        std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::back_inserter(vLine));
        if (vLine.size() > 3)
        {
            vLine.erase(vLine.begin(), vLine.begin() + (vLine.size() - 3));
        }
        // store vLine somewhere useful
    }
    
    推荐文章