从c++文本文件中读取有向图的邻接表

Read adjacency list of digraph from a text file in C++

本文关键字:有向图 读取 c++ 文本 文件      更新时间:2023-10-16

我有一个文本文件,每行有一定数量的整数。例子:

1 2 4
3 
0 4
2 3

这里的第一行表示第一个节点连接到编号为1、2和5的节点。空白行表示第4个节点没有连接到任何节点。

这给出了一个有向图。这个SO问题可能有帮助,但它假设每行有2个整数,而在这种情况下,它可以有从0到N-1的任意数量的整数(N是否)。节点)。

我只想知道如何读取这个文本文件。如果每行有两个整数,我可以做infile>> a>> b,怎么知道"n"或者行尾发生了。我是不是要求代码,使有向图。

链接问题的可接受答案已经向您展示了如何逐行读取,这是您需要为代码执行的操作,第一部分展示了如何从行(istringstream)中读取所有数字的循环。因为没有固定数量的条目,所以可能希望将它们存储在std::vector中。

我不认为这是作业,因为实际的主题是有向图。

因此一些代码。但是,你必须自己做错误处理。

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
typedef std::vector<int> nl_t;
typedef std::vector<nl_t> nll_t;
int main()
{
    std::ifstream is("test.dat");
    std::string str;
    nll_t nll;
    while(std::getline(is,str)) {
        std::istringstream ss(str);
        nl_t nl;
        int i;
        while(ss >> i) {
            nl.push_back(i);
        }
        nll.push_back(nl);
    }
}
/**
     Local Variables:
     compile-command: "g++ -g test.cc -o test.exe; ./test.exe"
     End:
*/

点击此链接http://www.c-plusplus.de/forum/p1940874 1940874。阅读代码就足够了。不需要理解德语文本。

在您的情况下,您必须将主程序的第18行从while( datei >> ws )改为while( datei ),并删除第23行和第24行。因为在你的例子中,空行是一个信息。

或者你的main可以这样:

ifstream file("input.txt");
if( !file.is_open() )
{
    cerr << ">Error by opening the filen";
    return -2;
}
for( int node1 = 1; file.good(); ++node1 )
{
    for( int node2; !is_endl(file) && file >> node2; )
        cout << "Node " << node1 << " is connected with " << node2 << endl;
}