在Boost图中添加自定义顶点

23
如果我有n个被定义为CElement类的元素,如何使用boost graph创建这些元素的顶点,并将它们连接起来呢? 我看过boost graph bundled props,但是我就是想不通这个问题。

很抱歉讲得不够清楚。CElements的实例是顶点。我希望能够添加、删除、连接和断开这些CElements的实例。我真的需要定义一个具有pt到CElement实例的结构体Vertex吗?还是有更优雅的方法? - dodol
2个回答

59

我不理解你想要做什么。你是想将一些数据与顶点关联起来吗?那么请使用打包属性。

//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";

还有其他设置属性的方法,但这里有一个示例可以启动。

希望我没有误解问题。


2
我认为,应该使用以下代码代替edge_t e = boost::add_edge(u,v,g): edge_t e; bool added; boost::tie(e,added) = boost::add_edge(u,v,g); - dodol
2
@Tristram “比使用捆绑属性更容易”的意思实际上就是您在这个回答中所描述的就是捆绑属性。=) - wjl
有没有一种方法可以动态创建对象edge(u,v)并查找其捆绑属性?这将在另一个函数中完成,该函数没有boost::tie(e,b) = boost::add_edge(u,v,g);可用,只有顶点索引。 - Budric
给定我的顶点数据int foo,是否有可能找到已经添加到图中的顶点描述符? - fferri

11

请注意,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"];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接