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

dod*_*dol 19 boost graph

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

Tri*_*ner 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";
Run Code Online (Sandbox Code Playgroud)

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

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

  • 我认为代替 edge_t e = boost::add_edge(u,v,g); 应该写edge_t e;添加了布尔值;boost::tie(e,added) = boost::add_edge(u,v,g); (2认同)
  • @Tristram"比使用捆绑属性更容易" - 你在这个答案中描述的正是*IS*捆绑属性.=) (2认同)

Jea*_*ier 5

请注意,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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

digraph G {
0[label="123"];
1[label="456"];
0->1 [label="Hello"];
}
Run Code Online (Sandbox Code Playgroud)