【发布时间】:2016-06-04 13:17:56
【问题描述】:
我想使用 boost 从文件中读取图表。输入文件包含边数,然后是成对的边。我想打印邻接列表。我尝试了以下代码。请帮帮我
#include <boost/graph/adjacency_list.hpp>
#include <fstream>
#include <boost/graph/graphviz.hpp>
using namespace std;
using namespace boost;
int main(){
typedef adjacency_list <listS, vecS, directedS> Graph;
typedef graph_traits<Graph>::vertex_descriptor index_vertex;
typedef boost::graph_traits <Graph>::edge_iterator edgeIt;
typedef boost::graph_traits<Graph>::vertex_iterator vertexIt;
// declare a graph object
Graph G;
std::ifstream infile("di.dat");
index_vertex n_vertices;
//int n_vertices;
if(infile >> n_vertices){
std::cout << n_vertices << endl; // read in number of vertices
}
while(infile)
{
int f;
int s;
infile >> f>> s;
// std::cout<<first<<second;
add_edge(f, s, G);
}
infile.close();
for(pair<vertexIt,vertexIt> vi = boost::vertices(G); vi.first != vi.second; ++vi.first) {
cout << *vi.first << endl;
}
for(pair<edgeIt,edgeIt> ei = boost::edges(G); ei.first != ei.second; ++ei.first) {
cout << source(*ei.first, G) << " -> " << target(*ei.first, G) << endl;
//cout << *ei.first << endl;
}
ofstream dotfile;
dotfile.open("test1.dot");
write_graphviz(dotfile, G);
system("xdot test1.dot");
return 0;
}
输入是
14
1 2
2 3
3 4
3 5
4 6
6 7
7 8
7 9
7 10
8 11
9 12
12 13
13 14
【问题讨论】:
-
如果您包含错误消息以及您正在使用的平台和编译器,将会很有帮助。
-
如果将for循环更改为
for (int i=0; ei != ei_end; ++ei, ++i),则可以完全删除ei_next。