Shambo
Shambo

Reputation: 946

Print boost graph with custom vertex label

I want to print a Boost Graph having custom(string) vertex labels instead of the default vertex numbering label 0,1,2...

I have initialized the graph as :

typedef adjacency_list <vecS, vecS, directedS, 
                        property<vertex_name_t,string>
                       > Graph;

Graph g;
set<string> names; 
map<string,Graph::vertex_descriptor> vertex ;

for(auto it = names.begin() ; it != names.end(); ++it )
       vertex[*it] =  add_vertex(*it,g) ;

Now how should I print this graph such that I get edges of the form abc -> xyz; instead of 1->2;

Upvotes: 2

Views: 3210

Answers (2)

hcc23
hcc23

Reputation: 1280

I am not a truly versed BGL user, but I see some issues in your approach:

1) It seems that your are declaring an internal property vertex_name but then use an external storage set<string>?

2) Independent of that, I don't see any code that actually populates the name, be it in the internal or the external case -- but I assume that you simply omitted that for brevity.

But now to a proposed solution: BGL actually comes with a method to do what you want: boost::print_graph :

using namespace boost;
typedef adjacency_list <vecS, vecS, directedS, 
                        property<vertex_name_t,string>
                       > Graph;
Graph g;

std::set<string> names;
// somehow populating names here...

// creating the vertices and storing the names as internal properties
for(auto it = names.begin() ; it != names.end(); ++it )
{ 
  auto v = add_vertex(g);
  put(vertex_name,g,/*vertex descriptor*/ *v,/*vertex name*/ *it);
}
print_graph(g,get(vertex_name,g)); //NOTE: you could also use an external property map or an adaptor

Upvotes: 1

Cubbi
Cubbi

Reputation: 47498

You could get that name from the vertex descriptors, for example

graph_traits<Graph>::edge_iterator it, end;
for(tie(it, end) = edges(g); it != end; ++it)
    std::cout << get(vertex_name, g)[source(*it, g)] << " -> "
              << get(vertex_name, g)[target(*it, g)] << '\n';

Upvotes: 4

Related Questions