【问题标题】:Read adjacency list of digraph from a text file in C++从 C++ 中的文本文件中读取有向图的邻接列表
【发布时间】:2014-03-21 14:58:00
【问题描述】:

我有一个文本文件,每行有一些整数。示例:

1 2 4
3 
0 4

2 3

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

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

我只想知道如何阅读这个文本文件。如果我每行有两个整数,我可以完成 infile >> a >> b。如何知道发生了“\n”或行尾。 我不是要求生成有向图的代码。

【问题讨论】:

  • DFS 可以从机构列表中重建图形,并从中提取大量信息。但我们不存在为你编写代码,所以你会被否决而被遗忘。
  • 您能否向我们展示您目前需要改进的方法? @MadScienceDreams 这是命令吗?

标签: c++ file-io graph directed-graph adjacency-list


【解决方案1】:

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

【讨论】:

  • 我编辑了这个问题。如何知道一行有多少个整数?
  • 你没有,你只是读入直到循环停止,然后将每个条目添加到向量中,如 Tobias 的答案所示。
【解决方案2】:

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

因此有一些代码。但是,您必须自己进行错误处理。

#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:
*/

【讨论】:

    【解决方案3】:

    点击此链接 http://www.c-plusplus.de/forum/p1940874#1940874。 看代码就够了。没有必要看懂德文。

    在您的情况下,您必须将主程序的第 18 行从 while( datei &gt;&gt; ws ) 更改为 while( datei ) 并删除第 23 和 24 行。因为在您的情况下,空行是一条信息。

    或者你的 main 可以是这样的:

    ifstream file("input.txt");
    if( !file.is_open() )
    {
        cerr << ">Error by opening the file\n";
        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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多