tags:

views:

296

answers:

2

Hi,

I am looking for a way to access vertex properties by using a key instead of vertex reference itself. For example, if I have

class Data
{
  public:
    std::string  name;
    unsigned int value; 
}; 
typedef boost::adjacency_list< boost::vecS, boost::vecS, boost::directedS, Data > Graph;
typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;

instead of using

Vertex vertex1 = boost::add_vertex( g );
g[vertex1].name  = "Alpha";
g[vertex1].value = 10;

I would like to have

g["Alpha"].name  = "Alpha";
g["Alpha"].value = 10;

Does a ready to use mechanism exist?

Thank you, Serge

+1  A: 

A ready to use mechanism doesn't exist since the adjacency_list concept cannot know that you wanna access your vertex property by a field in a struct.

I would prefer the way of having an additional map which maps the name of the data to the corresponding vertex. Further, you can encapsulate your algorithm in a class or a function, so that when adding a new vertex the map is filled automatically.

Rupert Jones
+2  A: 

I think I have found such mechanism. It is called labeled_graph and is a part of BGL. Instead of using adjacency_list, one can use a predefined wrapper labeled_graph:

typedef boost::labeled_graph<
    boost::adjacency_list< boost::vecS, boost::vecS, boost::directedS, Data >,
    std::string
> Graph;

After defining a graph like this, it is possible to access vertices in the following manner:

Graph g;

boost::add_vertex( "Alpha", g );
g["Alpha"].name  = "Alpha";
g["Alpha"].value = 10;

boost::add_vertex( "Beta", g );
g["Beta"].name  = "Beta";
g["Beta"].value = 20;

boost::add_edge_by_label( "Alpha", "Beta", g );

The side effect of this is that one need to use graph() member function to make some algorithms work:

std::vector< Graph::vertex_descriptor > container;
boost::topological_sort( g.graph(), std::back_inserter( container ) ) ;

For some reason, labeled_graph is not described in BGL documentation, but it appears in the example folder.

Thank you for reply, Serge

Serge C
Looking at the history of labeled_graph.hpp adapter, it looks like the file is relatively new. (Started to appear in Boost library release 1.40). Probably that is why it is not a part of the documentation yet,
Serge C