我不知道为什么整个矩阵都存储在第一行本身。如果有 N 行,该循环实际上会被调用 N 次。
这是matrix.dat
5
1 2 3
1 2 0 100
3 4 0
5 6 -1
0 9 10 11
#include <fstream>
#include <iterator>
#include <vector>
#include <iostream>
int main() {
std::vector<std::vector<int> > matrix;
std::ifstream infile("matrix.dat");
int num_rows;
infile>>num_rows;
//If there are 5 rows in the matrix, this loops DOES run 5 times.
for(int i=0;i<num_rows;i++){
matrix.push_back(std::vector<int>());
std::copy(
std::istream_iterator<int>(infile),
std::istream_iterator<int>(),
std::back_inserter(matrix[i])
);
}
// Printing the size of matrix. This correctly prints the value of num_rows
std::cout<<matrix.size()<<std::endl;
// Printing just 1st row, but that contains the entire matrix.
// Seems like copy always happens to matrix[0] only.
for(int j=0;j<matrix[0].size();j++)
std::cout<<matrix[0][j]<<" ";
}
最佳答案
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
int main()
{
std::vector< std::vector< int > > matrix;
std::ifstream infile( "matrix.dat" );
std::string s;
while( std::getline( infile, s ) )
{
std::string token;
std::vector< int > tokenisedLine;
std::istringstream line(s);
while( std::getline( line, token, ' ' ) )
tokenisedLine.push_back( atoi( token.c_str() ) );
matrix.push_back( tokenisedLine );
}
return 0;
}
这段代码应该做你想要的,但是它有点慢,复制和创建所有临时对象。但对于像您的示例这样的小文件,这会很好。
它使用您的测试数据编译并为我工作。
如您所见,它第一次使用 getline 两次是根据\n 字符拆分行,然后我们使用空格字符再次使用它。因此在使用这段代码时需要使用空格来分隔元素。
然后,一旦我们将 token 作为字符串,我们就可以使用 atoi 将其转换为 int。
HTH.
关于c++ - std::copy 从文件读取矩阵时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1780969/