我需要遍历图的边缘并检查每条边缘的权重。我没有修改边缘,因此我的函数需要对图形进行 const 引用。但是,我知道获得边缘权重的唯一方法是访问属性映射,这似乎违反了 const-ness。
void printEdgeWeights(const Graph& graph) {
typedef Graph::edge_iterator EdgeIterator;
std::pair<EdgeIterator, EdgeIterator> edges = boost::edges(graph);
typedef boost::property_map<Graph, boost::edge_weight_t>::type WeightMap;
// The following line will not compile:
WeightMap weights = boost::get(boost::edge_weight_t(), graph);
EdgeIterator edge;
for (edge = edges.first; edge != edges.second; ++edge) {
std::cout << boost::get(weights, *edge) << std::endl;
}
}
所以我必须这样做:
Graph& trust_me = const_cast<Graph&>(graph);
WeightMap weights = boost::get(boost::edge_weight_t(), trust_me);
有没有办法避免这种情况?
附带说明一下,属性映射查找会是恒定时间吗?
作为参考,这是我对 Graph 的定义。
struct FeatureIndex { ... };
typedef boost::property<boost::vertex_index_t, int,
FeatureIndex>
VertexProperty;
typedef boost::property<boost::edge_index_t, int,
boost::property<boost::edge_weight_t, int> >
EdgeProperty;
typedef boost::subgraph<
boost::adjacency_list<boost::vecS,
boost::vecS,
boost::undirectedS,
VertexProperty,
EdgeProperty> >
Graph;
谢谢!