【问题标题】:adding custom vertices to a boost graph将自定义顶点添加到提升图
【发布时间】:2011-03-07 05:19:12
【问题描述】:

如果我有 n 个使用类 CElement 定义的元素,如何使用 boost 图创建这些元素的顶点 - 并将它们也连接起来? 我见过 boost graph 捆绑的道具,但我就是想不通。

【问题讨论】:

  • 抱歉不清楚。 CElements 的实例是顶点。我希望能够添加、删除、连接和断开 CElements 的这些实例。我真的需要定义具有 pt 到 CElement 实例的 struct Vertex 还是有更优雅的方式?

标签: boost graph


【解决方案1】:

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

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

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

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

【讨论】:

  • 我认为不是 edge_t e = boost::add_edge(u,v,g);应该写 edge_te;布尔添加; boost::tie(e,add) = boost::add_edge(u,v,g);
  • @Tristram “比使用捆绑属性更容易” - 您在此答案中所描述的正是 IS 捆绑属性。 =)
  • 有没有办法动态创建对象 edge(u,v) 并查找它的捆绑属性?这将在没有 boost::tie(e,b) = boost::add_edge(u,v,g); 的不同函数中完成。可用,只有顶点索引。
  • 根据我的顶点数据int foo是否有可能找到已经添加到图中的顶点描述符?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多