c++ - 无法添加命名的顶点(根据教程)

标签 c++ boost-graph

我现在正在学习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/

相关文章:

c++ - 从 boost::adjacency_list 获取边属性(包括相关顶点)

c++ - boost 图 : Test if two vertices are adjacent

c++ - 有效地在 Boost BGL 图中找到所有可达的顶点

c++ - 如何使用 Boost 的 vf2_subgraph_iso 检测 multimap 上的子图同构?

c++ - is_lock_free() 在升级到 MacPorts gcc 7.3 后返回 false

c++ - 预声明类型定义的 boost::variant

C++函数指针作为模板

C++ 如何从一个模板类转换为另一个模板类?

c++ - 为什么我们不能使用两个具有不同类型但完全相同的成员的结构(或类)互换?

algorithm - Boost Graph 最大流算法找出最小 S/T 切割上的弧