C++ BGL邻接表中返回空边描述符的实现方案
无查询结果时返回空边的Boost图实现方案
Boost Graph库没有提供统一的graph_traits<G>::null_edge()常量,是因为不同图实现的边描述符类型差异较大,无法定义通用的无效默认值,但可以通过以下三种常用方案实现需求:
方案1:C++17及以上版本使用
std::optional包装返回值(最推荐)
这是类型最安全的实现,无需依赖边描述符的底层实现细节,查询成功返回对应边描述符,失败返回std::nullopt即可。
示例代码:#include <optional> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_traits.hpp> using Graph = boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS>; using VertexDesc = boost::graph_traits<Graph>::vertex_descriptor; using EdgeDesc = boost::graph_traits<Graph>::edge_descriptor; std::optional<EdgeDesc> get_edge_by_vertex(const Graph& g, VertexDesc u, VertexDesc v) { auto [find_res, exist] = boost::edge(u, v, g); return exist ? std::optional(find_res) : std::nullopt; }调用时通过
has_value()判断是否查到有效边即可。方案2:自定义空边常量(兼容C++11及更早版本)
对于Boost内置的所有常用图类型(adjacency_list、adjacency_matrix等),默认构造的边描述符和所有有效边描述符都不相等,可以自行封装全局的空边生成函数:
示例代码:template <typename Graph> inline typename boost::graph_traits<Graph>::edge_descriptor null_edge() { return typename boost::graph_traits<Graph>::edge_descriptor(); }查询失败时直接返回
null_edge<Graph>(),判断时将返回值和null_edge<Graph>()比较即可确认是否为有效边。方案3:直接返回
pair<EdgeDesc, bool>
完全复用Boost内置edge()接口的返回格式,第二个bool值标记边是否存在,无需引入额外依赖,适合需要兼容老版本C++的场景。
注意:如果使用自定义实现的Boost兼容图类型,需要先确认默认构造的边描述符确实与所有有效边描述符不相等,再使用方案2。
内容的提问来源于stack exchange,提问作者eddy
相关产品推荐
相关产品推荐

