如何将文件作为vector <vector <double >>读取?

Ric*_*lev 1 c++ vector c++11

我有这样的数据

4.0 0.8
4.1 0.7
4.4 1.1
3.9 1.2
4.0 1.0
Run Code Online (Sandbox Code Playgroud)

我写了我的程序

#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main() {
vector<double> v;
ifstream in("primer.dat");
double word;
while(in >> word)
v.push_back(word);
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
}
Run Code Online (Sandbox Code Playgroud)

但是现在我已经意识到,为了在我的代码中进一步计算,我需要数据(vector <vector> double).我宁愿不重塑矢量.是否可以将数据作为矢量矢量读取?

Vla*_*cow 6

请尝试以下方法

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <sstream>
#include <string>

int main()
{
    std::vector<std::vector<double>> v;
    std::ifstream in( "primer.dat" );
    std::string record;

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

    for ( const auto &row : v )
    {
        for ( double x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }        
}    
Run Code Online (Sandbox Code Playgroud)