简体   繁体   中英

C++ STL priority queue not sorting correctly

I want have a vector of Waypoint* objects that are sorted so that the waypoint with the lowest distance is at the top of the queue.

Here is my compare class:

class WaypointCompare {
    public:
        bool operator()(Waypoint* left, Waypoint* right) const {
            return left->getDistance() < right->getDistance();
        }
};

And here is how I'm initializing the queue:

std::priority_queue<Waypoint*, std::vector<Waypoint*>, WaypointCompare> queue;

Whenever I update the distance of a waypoint, my queue seems to not reorder correctly. Like for this example, shouldn't the Waypoint object with the smallest distance value be at the back (top) (index 10) of the queue? Here is an image of some debugging of the queue, I've noted what I think is wrong:

在此处输入图片说明

I think it may have something to do with my shaky understanding of pq's, or that I'm initializing all the distances to HUGE_VAL.

Whenever I update the distance of a waypoint, my queue seems to not reorder correctly.

No, it won't. The queue doesn't reorder itself if an element changes; doing so will just break the ordering. You'll need to remove and reinsert any element that changes in a way that affects the ordering.

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