我现在正在学习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);
看到它Live on Coliru
或者,按照我的喜好,使用
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);
看到它Live on Coliru
看起来似乎需要更多工作,但是它具有许多顶点/边缘属性,既轻松又灵活。您可以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);
关于c++ - 无法添加命名的顶点(根据教程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61091485/