[英]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.