繁体   English   中英

priority_queue运算符<实现麻烦

[英]priority_queue operator < implementation trouble

我有多个不同类型的事件,需要推入优先级队列,并确保它们按事件时间排序。

struct Event {
    double event_time;
    int type;
};

我使用如下类的EventCompare:

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

并初始化优先级队列:

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

当我将事件推送到优先级队列中时,它们仍未排序。 我的实现有问题吗?

我以以下方式生成事件:

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);
}

然后,我执行另一个类似的循环,但是重置rand种子,将action_time设置回0,对于类型1的事件,类型1的事件不会按event_time的顺序放置。

如果您打算将最早的事件(最低的event_time)放在队列的顶部,则需要反转自定义比较。 默认情况下,std :: priority_queue将最大的放在顶部:

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

这对我来说很好。 大肠杆菌的例子

暂无
暂无

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

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