从c++文本文件中读取有向图的邻接表
Read adjacency list of digraph from a text file in C++
我有一个文本文件,每行有一定数量的整数。例子:
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;
}
相关文章:
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- C++创建指向有向图中节点的指针数组
- 如何仅在 2 个节点之间获取最短路径,给定邻接列表有向图?
- 有向图 - 如何计算图中彼此顶点可到达的顶点数?
- C++计算有向图中的最短路径
- 使用非递归 DFS 检测有向图中的周期
- 如何将这些节点连接为有向图
- 如何使用广度优先搜索确定是否可以在有向图中到达顶点
- 在有向图中精确访问所有节点一次
- 在有向图中查找第二条最短路径
- 关于如何处理有向图的一个想法
- 找到有向图C 的最短路径
- 分析输入文件以创建有向图C++
- 在使用无序多映射实现的有向图中查找循环
- 如何找到在c++中实现的有向图的所有路径作为邻接列表
- 如何创建具有多个数据的节点的有向图
- 有向图中的广度优先搜索
- 查找路径的有向图邻接矩阵
- 从文件构建有向图
- 从c++文本文件中读取有向图的邻接表