Search code examples
c++boostgraphboost-graph

Why edge properties can't be changed within visitor in BGL?


I want to change edge weight when examine an edge, but it tells

error: assignment of member ‘EdgeProperty::weight’ in read-only object g[e].weight = 1/g[e].residual_capacity;

If there is a way to change edge properties within a function of a custom visitor? Thanks.

struct EdgeProperty{
float weight;
float capacity;
float residual_capacity;
};
class custom_dijkstra_visitor : public boost::default_dijkstra_visitor
{
public:
    template < typename Edge, typename Graph >
    void examine_edge(Edge e, Graph const & g)
    {
        g[e].weight = 1/g[e].residual_capacity;
    }
};

Solution

  • Finally I solved it by storing a Graph pointer in the visitor.

    Note though that presumably you pass the visitor to an algorithm. That algorithm has its own invariants. If you change the weights, e.g. dijkstra_shortest_paths may not terminate at all, or yield incorrect (suboptimal) results.

    If you want to change the weight according to the results of a previous algorithm and the algorithm uses (depends on) the weights, the safest course of action would be to store the "updated" weights in a separate map, and appy the changes afterwards.