Search code examples
c++boostgraphvizboost-graph

Simple dot output for Boost Graph edges labelled with basic types


Using bundled properties with the Boost Graph Library means it's very simple to create code to output a dot file compatible with graphviz:

#include <boost/graph/graphviz.hpp>

struct Edge { int i; };

int main()
{
  using namespace boost;
  typedef adjacency_list<vecS, vecS, directedS, no_property, Edge> Graph;
  Graph g;
  add_edge(0, 1, {123}, g);
  write_graphviz(std::cout, g, default_writer(),
                   make_label_writer(boost::get(&Edge::i,g)));
  return 0;
}

In the code above the edge property is defined using a struct called Edge. This struct contains only a single int; boost::get then provides make_label_writer with the necessary PropertyWriter.

If I would instead like to use a basic type, such as int or double, for the edge property instead, what are the arguments I now need to pass to make_label_writer? Can the code remain comparable to that above. For example, the adjacency_list could be declared as:

typedef adjacency_list<vecS, vecS, directedS, no_property, int> Graph;

Solution

  • You'd address the edge bundle directly.

    With bundled properties, the pointer-to-member property tag is implicitly applied to the value of the edge_bundle_t property (or vertex_bundle_t or graph_bundle_t as the case may be; Therefore you wouldn't want to use the same user-defined type for edge/vertex/graph bundles).

    Live On Coliru

    #include <boost/graph/adjacency_list.hpp>
    #include <boost/graph/graphviz.hpp>
    
    int main()
    {
        using namespace boost;
        typedef adjacency_list<vecS, vecS, directedS, no_property, int> Graph;
        Graph g;
        add_edge(0, 1, 123, g);
        write_graphviz(std::cout, g, default_writer(), 
                make_label_writer(boost::get(edge_bundle,g)));
    }
    

    Output:

    digraph G {
    0;
    1;
    0->1 [label=123];
    }