遍历一个常量 boost::graph 的边权重

6

我需要遍历一个图的边并检查每个边的权重。由于我不会修改这些边,因此我的函数接受一个对图的const引用。然而,我所知道的获取边权重的唯一方法是获取属性映射的访问权限,这似乎违反了const性。

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);

有没有办法避免这种情况发生?

顺便提一下,属性地图查找是否是常数时间?

供参考,这是我的图形定义。

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;

谢谢!

1个回答

5

供以后参考,我已经找到了。这个方法行不通。

const boost::property_map<Graph, boost::edge_weight_t>::type

但是 property_map 定义了 const_type。
boost::property_map<Graph, boost::edge_weight_t>::const_type

get()的文档在这个页面上: http://www.boost.org/doc/libs/1_51_0/libs/graph/doc/adjacency_list.html

(注:get()是一个函数名,涉及到it技术领域)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接