【问题标题】:boost::dijkstra_shortest_paths overwriting internal graph weights?boost::dijkstra_shortest_paths 覆盖内部图权重?
【发布时间】:2012-09-12 07:39:13
【问题描述】:

我正在使用 Boost Graph Library 来存储一个带有double 边权重和double 顶点权重的无向图。在我的代码中的几个地方,我需要应用 Dijkstra 算法来搜索最短路径。这工作得很好,直到我决定我想用我自己的权重临时覆盖存储的边缘权重(只是暂时的,图表权重不应被修改)。我的代码基本上是这样的:

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

虽然graph 在上面的代码中是一个const 引用,但是之后图的边权重会改变。我究竟做错了什么?或者更具体地说,如何临时覆盖加权图中的边权重?

显然,我可以简单地存储当前的边权重,用我的权重替换它们,然后再将它们改回来。但是,我确信有过错,我不想忽视这个问题。

【问题讨论】:

    标签: c++ dijkstra boost-graph


    【解决方案1】:

    我相信,我也有同样的问题 - 我想暂时(针对特定的搜索算法运行)修改边权重,而不是永久更改图形本身。经过一番搜索,我找到了这个,它允许您注册一个用于生成权重的函子。这用作 weight_map 参数:

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

    【讨论】:

    • 谢谢,有帮助。很抱歉花了这么长时间才接受答案。
    猜你喜欢
    • 2011-10-06
    • 2015-02-19
    • 2015-04-30
    • 2015-09-26
    • 2018-08-01
    • 2017-05-11
    • 2012-09-06
    • 1970-01-01
    相关资源
    最近更新 更多