2013-10-04 50 views
1

我有多個不同類型的事件需要推入優先級隊列,並確保它們按事件時間排序。priority_queue運算符<執行問題

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

我那麼做的另一個類似的循環,但重置蘭特種子,ACTION_TIME背部設置爲0,而對於1型事件,與事件類型1不按照event_time的順序放置。

+1

你是什麼意思沒有排序?你怎麼知道? –

+0

我的意思是當我從隊列的頭部開始彈出時,值不會從最低到最高。 – rcell

+0

你應該通過'const'參數來引用參數:'bool operator()(const Event&a,const Event & b);' –

回答

1

如果您打算將最老的事件(event_time最低)放在隊列頂部,則需要反轉自定義比較。默認情況下,std :: priority_queue將最大值置頂:

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

這對我很好。示例在coliru

+0

我改變了我的比較,並添加到我的問題,我如何生成我的事件 – rcell

+0

請參閱修改的coliru使用您的方式生成事件:http: //coliru.stacked-crooked.com/a/d80a0fae07062703 – goji