c++ - 遍历 const boost::graph 的边权重

标签 c++ boost-graph

我需要遍历图的边并检查每条边的权重。我没有修改边,因此我的函数采用对图形的常量引用。但是,我知道获得边权重的唯一方法是访问属性映射,这似乎违反了常量性。

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;

谢谢!

最佳答案

为了将来引用,我找到了它。这行不通

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

关于c++ - 遍历 const boost::graph 的边权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12501188/

相关文章:

c++ - C++中的开源行进立方体算法?

c++ - 在 C 程序中使用 C++ 代码,反之亦然

c++ - 在 boost 图库中为深度优先搜索提供颜色图时遇到问题

c++ - 如何使自定义图形适合 boost 图形库模板?

c++ - 在 boost::graph 中访问 std::shared_ptr 的成员函数?

c++ - 不允许循环引用的 boost 图

c++ - 我可以覆盖 dll 中的版本 block 吗?

c++ - 使用指针访问 obj vector 中的第二个元素时出现段错误

c++ - C++ 中二进制文件的读写

c++ - boost BGL 传递减少