Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through edge weights of a const boost::graph

I need to iterate through the edges of a graph and examine the weight of each edge. I'm not modifying the edges, therefore my function takes a const-reference to a graph. However, the only way I know to get the edge weights is to get access to the property map, which seems to violate 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;
  }
}

So I have to do this:

Graph& trust_me = const_cast<Graph&>(graph);
WeightMap weights = boost::get(boost::edge_weight_t(), trust_me);

Is there a way to avoid this?

On a side note, will the property map lookups be constant time?

For reference, here's my definition of 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;

Thanks!

like image 908
Jack Valmadre Avatar asked Sep 19 '12 19:09

Jack Valmadre


1 Answers

For future reference, I found it. This won't work

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

but property_map defines a const_type

boost::property_map<Graph, boost::edge_weight_t>::const_type

The documentation for get() is on this page: http://www.boost.org/doc/libs/1_51_0/libs/graph/doc/adjacency_list.html

like image 119
Jack Valmadre Avatar answered Nov 10 '22 08:11

Jack Valmadre