2011-10-18 38 views
5

我想知道什麼時候C++ STL priority_queue自己排序。我的意思是insert當你把push這個物品放入正確的地方時,還是它自己排序並給你最高優先級的物品,當你peekpop出來的時候呢?我問這是因爲我的priority_queue<int>將包含一個數組的索引,可能有值更新,我希望它在我做pq.top();時更新。什麼時候std :: priority_queue <>自己排序?

#include <cstdio> 
#include <algorithm> 
#include <queue> 
using namespace std; 

int main() { 
    priority_queue<int> pq; 
    pq.push(2); 
    pq.push(5); //is the first element 5 now? or will it update again when I top() or pop() it out? 
    return 0; 
} 

謝謝。

+0

你可以很容易發現這些特性,因爲喜歡'map'它需要一個比較謂詞。如果您提供比較謂詞,並在每次比較時打印到控制檯(例如),則會在調用時(以及在哪些值上)在活動中見證。 –

回答

10

工作期間push()pop(),其調用底層堆修改功能(push_heap()pop_heap())來完成。 top()需要一段時間。

+0

真棒,這正是我想聽到的。一旦時間限制消失,我會將其標記爲答案。 –

+1

示例[here](http://www.sgi.com/tech/stl/priority_queue.html)演示的行爲真的很好 –

+0

@StanleyCen:很高興我能幫忙,雖然我真的只是切斷了信息[某些網站](http://www.cplusplus.com/reference/stl/priority_queue/pop/)... –

相關問題