如何将文件读取为vector< vector< double>&gt ;? [英] How to read file as vector<vector<double>>?

查看:85
本文介绍了如何将文件读取为vector< vector< double>&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据

4.0 0.8
4.1 0.7
4.4 1.1
3.9 1.2
4.0 1.0

我已经编写了程序

#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;
}

但是现在我意识到,为了在代码中进行进一步的计算,我需要数据为( vector< vector> double)。我不希望对矢量进行整形,是否有可能将数据读取为矢量的矢量?

But now I have realized that for further calculations in my code,I need data as (vector <vector> double).I would prefer not to reshape the vector.Is it possible to read data as vector of vectors?

推荐答案

尝试以下操作

#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;
    }        
}    

这篇关于如何将文件读取为vector&lt; vector&lt; double&gt;&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆