Search code examples
c++boostgraphboost-graph

Find Boost BGL vertex by a key


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?


Solution

  • 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