rebuilding a std::priority_queue

Started by
2 comments, last by XXX_Andrew_XXX 16 years, 1 month ago
Hi I'm using a priority queue to organize a large number of Vertex's by a their '.getDist()' value. Smallest dist on top. I change the dist value externally (only to a smaller value, never bigger) sometimes, and I would like the pqueue to re-adjust itself. I thought simply pop()ing the top of the pqueue would do the trick, since it would cause it to percolate up/down, but I'm seeing cases where it fails to organize the Vertex's correctly. I also thought about rebuilding the pqueue each time form the old one, but can't find a way to do it. BTW, the complexity time must be very good. Any suggestions? Thanks for any input
Advertisement
std::priority_queue isn't designed for objects that change their heap value. If you really want to do this, manually manage your heap with the functions std::make_heap(), std::pop_heap() and std::push_heap(). When you change your heap values rerun std::make_heap().
Thanks SiCrane, looks like this will work fine for me. Do you mind giving me an example of how to use make_heap with a compare function? The value to compare is vertexName->getDist(). (The heap will keep pointers to Vertex's). Thanks
The standard c++ heap API works on containers whose items support strict-weak ordering. The simplest implementation would be:

struct VertexDistancePredicate {    bool operator()(const Vertex* v0, const Vertex* v1) const    {        return v0->getDist() < v1->getDist();    }};...std::vector<Vertex*> q;VertexDistancePredicate pred;push_heap(q.begin(), q.end(),pred);pop_heap(q.begin(), q.end(),pred);make_heap(q.begin(),q.end(),pred);

This topic is closed to new replies.

Advertisement