调用boost::dijkstra_shortest_paths时boost::get匹配失败如何解决?
问题原因
你使用自定义gG_edge_property作为边的bundled属性时,没有为Boost.Graph的boost::edge_weight_t标签绑定对应的属性字段,导致boost::get(boost::edge_weight, Graph)无法识别要读取边的哪个字段作为权重,因此抛出模板匹配错误。
你参考的官方示例默认已经完成了edge_weight标签和边属性的关联,所以可以直接使用标准写法,自定义属性场景需要额外做映射配置。
解决方法
方法1:直接传入成员属性映射(推荐,无需额外特化模板)
如果你的gG_edge_property中存储边权重的字段名为weight(类型为double,和你传入Dijkstra的成本类型一致),直接把Dijkstra调用中的WeightMap参数替换为成员属性映射即可:
boost::dijkstra_shortest_paths(Graph, endVert, &predecessors[0], &costs[0], // 替换为你边属性里对应权重的成员指针 boost::get(&gG_edge_property::weight, Graph), boost::get(boost::vertex_index, Graph), std::less<double>(), std::plus<double>(), (std::numeric_limits<double>::max)(), double(), boost::dijkstra_visitor<boost::null_visitor>());
方法2:为自定义属性注册edge_weight标签映射
如果你需要保持boost::get(boost::edge_weight, Graph)的标准写法,需要在全局boost命名空间下特化属性映射规则:
// 假设gG_edge_property中权重字段为 double weight; namespace boost { template<> struct property_map<graph_type, edge_weight_t> { typedef member_property_map<gG_edge_property, double, &gG_edge_property::weight> type; typedef member_property_map<const gG_edge_property, const double, &gG_edge_property::weight> const_type; }; inline property_map<graph_type, edge_weight_t>::type get(edge_weight_t, graph_type& g) { return property_map<graph_type, edge_weight_t>::type(); } inline property_map<graph_type, edge_weight_t>::const_type get(edge_weight_t, const graph_type& g) { return property_map<graph_type, edge_weight_t>::const_type(); } }
完成特化后即可使用原标准写法调用Dijkstra接口。
注意事项
- 确保边权重字段的类型和Dijkstra接口中传入的成本计算类型一致,避免出现隐式类型转换导致的二次模板匹配错误
- 如果权重需要动态计算而非直接存储为边属性,可以使用
boost::function_property_map传入自定义权重计算逻辑,无需修改属性定义
内容的提问来源于stack exchange,提问作者DasBanzai
相关产品推荐
相关产品推荐

