adding custom vertices to a boost graph

后端 未结 2 1502
猫巷女王i
猫巷女王i 2020-12-02 16:16

If I have n elements defined with class CElement, how can one create vertices of those elements with boost graph - and connect them also? I\'ve seen boost graph bundled pro

2条回答
  •  余生分开走
    2020-12-02 16:36

    Note that Boost.Graph has overloads which allow to simplify Tristram's answer:

    #include 
    #include 
    #include 
    
    int main()
    {
        struct Vertex { int foo; };
        struct Edge { std::string blah; };
    
        using namespace boost;
        using graph_t  = adjacency_list;
        using vertex_t = graph_traits::vertex_descriptor;
        using edge_t   = graph_traits::edge_descriptor;
    
        //Instantiate a graph
        graph_t g;
    
        // Create two vertices in that graph
        vertex_t u = boost::add_vertex(Vertex{123}, g);
        vertex_t v = boost::add_vertex(Vertex{456}, g);
    
        // Create an edge conecting those two vertices
        boost::add_edge(u, v, Edge{"Hello"}, g);
    
        boost::write_graphviz(std::cout, g, [&] (auto& out, auto v) {
           out << "[label=\"" << g[v].foo << "\"]";
          },
          [&] (auto& out, auto e) {
           out << "[label=\"" << g[e].blah << "\"]";
        });
        std::cout << std::flush;
    }
    

    Output:

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

提交回复
热议问题