2016-12-30 105 views
0

我發現priority_queue的構造函數http://www.cplusplus.com/reference/queue/priority_queue/priority_queue/是這樣的:C++的優先級隊列構造

priority_queue (const Compare& comp, const Container& ctnr); 

,但我發現的例子是這樣的:

std::priority_queue<int, std::vector<int>, std::greater<int> > q2; 

什麼是這兩個構造函數之間的區別?

我已經嘗試過他們兩個,但第一個沒有工作,priority_queue沒有從小到大排序。下面是代碼:

priority_queue<greater<int>, vector<int>> pq; 
pq.push(4); 
pq.push(2); 
pq.push(1); 
pq.push(3); 
pq.push(5); 

for (int i = 0; i < 5; i++) { 
    cout << pq.top() << endl; 
    pq.pop(); 
} 

結果還是5,4,3,2,1

+0

您似乎對構造函數和聲明之間的區別感到困惑。 –

+0

@SamVarshavchik你讓我錯了,我的觀點是第一個需要兩個參數,第二個需要三個參數。我需要編輯我的問題一點點,這是令人困惑的。 – myyukiho

+0

第二個實際上需要零參數。檢查[更好的參考](http://en.cppreference.com/w/cpp/container/priority_queue)並嘗試理解模板化變量聲明和構造函數之間的區別。 –

回答

2

什麼是這兩個構造函數之間的區別?

其中之一是構造函數;另一個不是。

typedef只是創建一個類型別名,稱爲mypq_type。當您創建此類型的對象時,您仍然會傳遞這些相同的構造函數參數。

+0

對不起,我原來的問題很混亂,我已經提出澄清。 – myyukiho

+0

@myyukiho:你還在比較一個構造函數與不是構造函數的東西。 –