简体   繁体   中英

boost::dijkstra_shortest_paths overwriting internal graph weights?

I am using the Boost Graph Library to store an undirected graph with double edge weights and double vertex weights. At several places in my code, I need to apply Dijkstra's algorithm in order to search for shortest paths. This works quite well until I decided I wanted to temporarily override the stored edge weights by my own weights (only temporarily, the graph weights shall not be modified). My code basically looks like this:

  // Initial typedefs

  typedef boost::property<boost::edge_weight_t, double> edge_weight_t;
  typedef boost::property<boost::vertex_discover_time_t, double> vertex_weight_t;
  typedef boost::adjacency_list<boost::vecS,
                                boost::vecS,
                                boost::undirectedS,
                                vertex_weight_t,
                                edge_weight_t> graph_t;

 // In a function, where graph is a const reference of type graph_t

 std::vector<double> pathLengths( boost::num_vertices( graph ) );

 boost::property_map<graph_t, boost::edge_weight_t>::type weightMap;
 boost::graph_traits<graph_t>::edge_iterator e_it, e_it_end;
 for( boost::tie( e_it, e_it_end ) = boost::edges( graph );
      e_it != e_it_end;
      ++e_it )
 {
   weightMap[ *e_it ] = 1.0;
 }

 boost::dijkstra_shortest_paths( graph,
                                 boost::vertex( vertex, graph ),
                                 boost::distance_map( &pathLengths[0] ).weight_map( weightMap ) );

Although graph is a const reference in the code above, the edge weights of the graph will be changed afterwards. What am I doing wrong? Or more specifically, how can I temporarily override the edge weights in a weighted graph?

Obviously, I could simply store the current edge weights, replace them by my weights, and change them back afterwards. However, I am convinced that I am at fault, and I do not want ignore this problem.

I had, I believe, the same issue - I wanted to temporarily (for a specific run of a search algorithm) modify edge weights, without permanently changing the graph itself. After some searching, I found this, which allows you to register a functor that is used to generate weights. This is used as the weight_map parameter:

http://www.boost.org/doc/libs/1_51_0/boost/property_map/function_property_map.hpp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM