使用`boost::dynamic_properties`(请参见
此处)和`boost::write_graphviz_dp`(请参见
此处),您可以输出具有自定义顶点和边`struct`中定义的属性的图形。要将属性注册到`boost::dynamic_properties`对象中,您必须使用保留的
属性,例如`label`,`weight`等。
一个注意事项是BOOST库(我正在使用1.82.0版本)仅支持`"node_id"`作为节点ID的属性名称,而当前的GraphViz标准使用`"id"`代替。
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <fstream>
struct Vertex {
int some_int;
std::string name;
};
struct Edge {
double weight;
};
using DirectedSimpleGraph =
boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, Vertex,
Edge>;
using VertexSpec = boost::graph_traits<DirectedSimpleGraph>::vertex_descriptor;
using EdgeSpec = boost::graph_traits<DirectedSimpleGraph>::edge_descriptor;
int main() {
DirectedSimpleGraph graph;
boost::dynamic_properties dp;
dp.property("node_id", boost::get(&Vertex::some_int, graph));
dp.property("label", boost::get(&Vertex::name, graph));
dp.property("weight", boost::get(&Edge::weight, graph));
VertexSpec v0 = boost::add_vertex(Vertex{0, "Zero"}, graph);
VertexSpec v1 = boost::add_vertex(Vertex{1, "One"}, graph);
VertexSpec v2 = boost::add_vertex(Vertex{2, "Two"}, graph);
VertexSpec v3 = boost::add_vertex(Vertex{3, "Three"}, graph);
boost::add_edge(v0, v1, Edge{1.0}, graph);
boost::add_edge(v0, v2, Edge{2.0}, graph);
boost::add_edge(v2, v3, Edge{3.0}, graph);
std::ofstream graph_file_out("./out.gv");
boost::write_graphviz_dp(graph_file_out, graph, dp);
}