Weight map as function in Boost Graph Dijkstra algorithm

前端 未结 1 955
生来不讨喜
生来不讨喜 2020-12-10 19:50

I\'m using Boost Graph Libraries and need to use a weightmap which is not constant, but which is a function of a parameter K (i.e. the edge costs depend on K). In practice,

相关标签:
1条回答
  • 2020-12-10 20:22

    There are a number of property map flavours. In particular one is the transform_value_property_map can be used here.

    Simple Approach C++03

    Assuming c++03 you'd write:

    Live On Coliru

    #include <boost/property_map/transform_value_property_map.hpp>
    #include <boost/bind.hpp>
    
    // ...
    
    boost::dijkstra_shortest_paths(g, a, boost::predecessor_map(&preds[0]).weight_map(
                boost::make_transform_value_property_map(
                    boost::bind(&Edge::getWeight ,_1, 2), 
                    boost::get(boost::edge_bundle, g))
            ));
    

    Cleaner C++11

    Live On Coliru

    auto wmap = make_transform_value_property_map([](Edge& e) { return e.getWeight(2); }, get(boost::edge_bundle, g));
    boost::dijkstra_shortest_paths(g, a, boost::predecessor_map(&preds[0]).weight_map(wmap));
    

    You can drop the boost/bind.hpp include.

    Bonus: drop the getWeight() member function

    Live On Coliru

    You don't actually need it. You could write a Phoenix actor in-place:

    #include <boost/phoenix.hpp>
    using boost::phoenix::arg_names::arg1;
    
    auto wmap = make_transform_value_property_map(2 * (&arg1->*&Edge::weight), get(boost::edge_bundle, g));
    

    Or use c++11 again:

    Live On Coliru

    auto wmap = make_transform_value_property_map([](Edge& e) { return e.weight * 2; }, get(boost::edge_bundle, g));
    
    0 讨论(0)
提交回复
热议问题