0

问题是文本文件中的数据编辑。文本文件包含五列。

1 | 2 | 3 | 4 | 5 |

1 2 4 4 1
2 3 4 4 3
3 4 5 0 0

目标是在上面的第 1 列和第 2 列中移动到第 4 列和第 5 列(值​​​> 0)或跟进:

1 | 2 | 3 | 4 | 5 |

1 2 4 0 0
2 3 4 0 0
3 4 5 0 0
4 1 0 0 0
4 3 0 0 0

如何做到这一点?有人可以告诉我一个如何用 C++ 做到这一点的例子std::vector吗?

那将不胜感激。

4

2 回答 2

2

我同意约阿希姆的观点。此外,在阅读文件时,使用back_inserteristream_iteratorstringstream您的生活更轻松:

vector<vector<double> > contents;

/* read file */
{
    ifstream inFile( "data.txt" );
    for ( string line; inFile; getline( inFile, line ) ) {
        stringstream line_stream( line );
        vector<double> row;
        copy( istream_iterator<double>( line_stream ), istream_iterator<double>(),
            back_inserter(row) );
        contents.push_back( row );
    }
}

这会将整个文件读入contents. 您需要包括sstreamalgorithmiteratoriosrteamfstreamstringvector

Now you can easily process your file with a for loop and accessing the numbers with contents[i][j]. If I understand you correctly this is what I think you want to do:

/* process file */
unsigned int n = contents.size();
for ( unsigned int i=0; i < n; ++i ) {
    vector<double> row( 5, 0. );
    bool add_row = false;
    if ( contents[i].size() >= 5 ) {
        for ( unsigned int j=3; j<4; ++j ) {
            double value = contents[i][j];
            contents[i][j] = 0.;
            if ( value > 0 ) {
                add_row = true;
                row[j-3] = value;
            }
        }
        if ( add_row == true ) {
            contents.push_back( row );
        }
    }
}

Now to write the file to stdout, simply:

/* write file */
for ( unsigned int i=0; i < contents.size(); ++i ) {
    copy( contents[i].begin(), contents[i].end(), ostream_iterator<double>( cout, " " ) );
    cout << endl;
}
于 2013-10-07T14:19:31.017 回答
0

有一个向量的向量。对于每一行,将每个数字读入一个子向量。然后写出每个子向量的前三个值,然后是每个子向量的最后两个值。

于 2013-10-07T13:51:26.890 回答