我现在正在学习BGL,却为此找到了tutorial。一切正常,直到到达add_named_vertex函数为止。这是我拥有的一段代码,无法正常运行(和教程):
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <type_traits>
#include <iostream>
#include <sstream>
#include <string>
boost::adjacency_list<
boost::vecS,
boost::vecS,
boost::directedS,
boost::property<boost::vertex_name_t, std::string>
>
create_empty_graph() { return {}; }
template<typename graph, typename name_type>
typename boost::graph_traits<graph>::vertex_descriptor
add_named_vertex(const name_type& vertex_name, graph& g) noexcept {
const auto vd = boost::add_vertex(g);
auto vertex_name_map = get(boost::vertex_name, g);
put(vertex_name_map, vd, vertex_name);
return vd;
}
int main()
{
auto g = create_empty_graph();
const auto va = add_named_vertex("One", g);
const auto vb = add_named_vertex("Two", g);
boost::add_edge(va,vb, g);
std::stringstream f;
boost::write_graphviz(f, g);
std::cout << f.str() << std::endl;
return 0;
}
我希望:
digraph G {
0[label=One];
1[label=Two];
0->1;
}
但是这是我得到的:
digraph G {
0;
1;
0->1;
}
如您所见,此代码的输出中没有标签。你能告诉我,我想念什么?这是预期的行为吗?尝试了clang ++和gcc以及Boost版本(1.69-1.71)的范围。
是,这是预期的行为。要打印标签,请添加属性编写器:
auto vlw = boost::make_label_writer(boost::get(boost::vertex_name, g));
boost::write_graphviz(f, g, vlw);
或者,根据我的喜好,使用write_graphviz_dp
使用dynamic_properties
:
boost::dynamic_properties dp;
dp.property("node_id", boost::get(boost::vertex_index, g));
dp.property("label", boost::get(boost::vertex_name, g));
boost::write_graphviz_dp(f, g, dp);
似乎需要更多工作,但它具有许多顶点/边缘属性,既简单又灵活。您可以search my answers来举例说明。
以上两种解决方法均打印
digraph G {
0[label=One];
1[label=Two];
0->1 ;
}
您不需要add_named_vertex
功能。您可以直接使用boost::add_vertex
初始化属性:
const auto va = add_vertex({"One"}, g);
const auto vb = add_vertex({"Two"}, g);
add_edge(va, vb, g);