如何通过读取文件填充向量? [英] How to fill vectors by reading a file?

查看:67
本文介绍了如何通过读取文件填充向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取包含邻接表的文件

I am trying to read a file which contains the adjacency list as

1 37 79 164 15

2 123 134 10 141 13

1 37 79 164 15
2 123 134 10 141 13

其中每行的第一个数字是顶点,其后的数字是它的相邻顶点。

where first number in every line is vertex and following numbers are its adjacent vertices.

这是我的代码从文件中读取。我已经能够在字符串中放置一行,但是不知道如何继续填充向量。

This is my code to read from the file . I have been able to put a line in a string but don't know how to proceed to populate the vector.

    ifstream ifs;
string line;
ifs.open("kargerMinCut.txt");
std::vector<vector <int> > CadjList(vertices);
while(getline(ifs,line)){
}

任何建议

推荐答案

您可以在sstream标头中使用 stringstream

You can use stringstream in the sstream header.

ifstream ifs;
string line;
ifs.open("kargerMinCut.txt");
std::vector<vector <int> > CadjList(vertices);
while(getline(ifs,line)){

    // transfer the line contents to line_stream.
    stringstream line_stream( line );

    // transfer line_stream to int variables.
    int tail_node;
    if ( line_stream >> tail_node ) // now do whatever you want with it.
    {
        int head_node;
        while ( line_stream >> head_node )
            CadjList[tail_node].push_back( head_node );
    }    
}

这篇关于如何通过读取文件填充向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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