简体   繁体   English

priority_queue运算符<实现麻烦

[英]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: 我使用如下类的EventCompare:

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. 然后,我执行另一个类似的循环,但是重置rand种子,将action_time设置回0,对于类型1的事件,类型1的事件不会按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. 如果您打算将最早的事件(最低的event_time)放在队列的顶部,则需要反转自定义比较。 By default std::priority_queue puts the greatest at the top: 默认情况下,std :: priority_queue将最大的放在顶部:

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

This works fine for me. 这对我来说很好。 Example at coliru 大肠杆菌的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM