将自定义顶点添加到增强图

时间:2010-06-23 08:43:41

标签: boost graph

如果我有使用类CElement定义的n个元素,那么如何使用boost图创建这些元素的顶点 - 并将它们连接起来? 我见过提升图捆绑道具,但我无法想出这个。

2 个答案:

答案 0 :(得分:52)

我不明白你想要做什么。您想将一些数据与顶点相关联吗?然后使用捆绑属性。

//Define a class that has the data you want to associate to every vertex and edge
struct Vertex{ int foo;}
struct Edge{std::string blah;}

//Define the graph using those classes
typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, Vertex, Edge > Graph;
//Some typedefs for simplicity
typedef boost::graph_traits<Graph>::vertex_descriptor vertex_t;
typedef boost::graph_traits<Graph>::edge_descriptor edge_t;

//Instanciate a graph
Graph g;

// Create two vertices in that graph
vertex_t u = boost::add_vertex(g);
vertex_t v = boost::add_vertex(g);

// Create an edge conecting those two vertices
edge_t e; bool b;
boost::tie(e,b) = boost::add_edge(u,v,g);


// Set the properties of a vertex and the edge
g[u].foo = 42;
g[e].blah = "Hello world";

设置属性的其他方法,但你有一个示例来引导。

我希望我没有误解这个问题。

答案 1 :(得分:3)

请注意,Boost.Graph有重载,可以简化Tristram的答案:

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <iostream>

int main()
{
    struct Vertex { int foo; };
    struct Edge { std::string blah; };

    using namespace boost;
    using graph_t  = adjacency_list<listS, vecS, directedS, Vertex, Edge >;
    using vertex_t = graph_traits<graph_t>::vertex_descriptor;
    using edge_t   = graph_traits<graph_t>::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;
}

输出:

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