从C ++中的文本文件中读取有向图的邻接列表 [英] Read adjacency list of digraph from a text file in C++
问题描述
我有一个文本文件,每行都有一些整数.示例:
I have a text file which has some number of integers in each line. Example:
1 2 4
3
0 4
2 3
第1行表示第一个节点已连接到编号为1、2和5的节点.空行表示第4个节点未与任何节点连接.
Here 1st line means that the 1st node is connected to nodes numbered 1, 2 and 5. Blank line means 4th node isn't connected to any node.
这给了我一个有向图. 此SO问题可能会有所帮助,但它假设每行包含2个整数,而在这种情况下,它可以具有从0到N-1(N是节点数)的任意数量的整数.
This gives me a directed graph. This SO question might have been helpful but it assumes each line to have 2 integers, whereas in this case it can have any number of integers from 0 to N-1(N is no. of nodes).
我只想知道如何阅读此文本文件.如果每行有两个整数,则可以完成infile >> a >> b.如何知道发生"\ n"或行尾. 我不是要求提供可生成有向图的代码.
I just want to know how to read this text file. If I had two integers per line, I could have done infile >> a >> b. How to know that "\n" or end of line has occured. I am not asking for code that makes directed graph.
推荐答案
我不认为这是家庭作业,因为主要主题是有向图.
I do not think that this is homework, since the acutal topic are digraphs.
因此有一些代码.但是,您必须自己处理错误.
Therefore some code. But, you have to do the error handling yourself.
#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:
*/
这篇关于从C ++中的文本文件中读取有向图的邻接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!