如果我有n个被定义为CElement类的元素,如何使用boost graph创建这些元素的顶点,并将它们连接起来呢?
我看过boost graph bundled props,但是我就是想不通这个问题。
我不理解你想要做什么。你是想将一些数据与顶点关联起来吗?那么请使用打包属性。
//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";
还有其他设置属性的方法,但这里有一个示例可以启动。
希望我没有误解问题。
int foo
,是否有可能找到已经添加到图中的顶点描述符? - fferri请注意,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"];
}