boost graph create graph in loop from txt file

question might be related to: Using boost graph library: how to create a graph by reading edge lists from file

however the answer did not really help me.

I want to create a graph using boost's adjacency_list class. The data is in a .txt file with two columns.

Sample:

5 14
7 2
3 18
21 207
...

It would be great if I could just do the following:

std::ifstream data("data.txt");
typedef adjacency_list<> Graph;
Graph g; 
while (data >> nodeA >> nodeB){
   add_edge(nodeA, nodeB, g);
} 

which, as already discussed here: boost graph understanding vertex creation behaviour

does not work for the reasons discussed in the article. I have also gone through various examples including from the boost graph documentary: http://www.boost.org/doc/libs/1_36_0/libs/graph/example/family-tree-eg.cpp (which are all by "hand"),

or from the book "Boost Graph Library" p.44 (which I can't seem to compile). So after several days of trial and error and looking through the above mentioned sources I still can"t figure out how to properly create a graph from a file.

Ideally, I would like to proceed as following:

while (data >> nodeA >> nodeB){
   graph_traits<Graph>::vertex_descriptor *newVertex = new graph_traits<Graph>::vertex_descriptor;
   newVertex = vertex(nodeA,g); 
   graph_traits<Graph>::vertex_descriptor *otherVertex = new graph_traits<Graph>::vertex_descriptor;
   otherVertex = vertex(nodeB,g); 
   add_edge(newVertex, otherVertex,g);
}

similar to: www.boost.org/doc/libs/1_56_0/libs/graph/example/undirected_adjacency_list.cpp

however I get a compilation error.

Anyway I would really appreciate any help to figure out how create a graph from a txt file.

Thank you guys in advance and best wishes.


which, as already discussed here: boost graph understanding vertex creation behaviour does not work for the reasons discussed in the article

I don't see an immediate problem. Unless your vertices are very sparse (eg you have a single node id of, say, 99,999,999,999 and the memery usage poses a problem).

Otherwise, you could either

  • keep a (bi)map of id -> vertex_descriptor
  • use vertex properties doc
  • 链接地址: http://www.djcxy.com/p/51060.html

    上一篇: 在BGL图形的路径中寻找哪条平行边缘被使用?

    下一篇: boost图形从txt文件循环创建图形