简体   繁体   中英

priority_queue operator < implementation trouble

I have multiple events of different types that I need to push into a priority queue and make sure they are sorted by the event time.

struct Event {
    double event_time;
    int type;
};

I use a class EventCompare like so:

class EventCompare {
public:
    bool operator()(Event &a, Event &b) {
        return a.event_time > b.event_time;
    }
};

and initialize the priority queue:

priority_queue<Event, vector<Event>, EventCompare> event_scheduler;

When I push Events into the priority queue, they are still not sorted. Is there something wrong with my implementation?

I generate my Events in such a way:

srand((unsigned int)time(NULL));
while(action_time < 100) {
    u = (double)rand()/(double)RAND_MAX;
    action_time += -log(u)/25;
    Event e = {action_time, 0};
    event_scheduler.push(e);
}

I then do another similar loop but resetting the rand seed, setting action_time back to 0, and for an event with type 1, the event with type 1 does not get placed in order of event_time.

If you're intending for the oldest events (event_time lowest) to be at top of the queue, you need to reverse your custom compare. By default std::priority_queue puts the greatest at the top:

class EventCompare {
public:
    bool operator()(Event &a, Event &b) {
        return a.event_time > b.event_time;
    }
};

This works fine for me. Example at coliru

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