文章目錄
C++ 優先順序隊列(priority_queue)
優先順序隊列顧名思義是根據元素的優先順序被讀取,介面和queues非常相近。程式員可以通過template參數指定一個排序準則。預設的排序準則是利用operator< 形成降序排列,那麼所謂“下一個元素”就是“數值最大的元素”。
如果同時存在若干個數值最大的元素,無法確知究竟哪一個會入選。
標頭檔:<queue>
在檔案 <queue> 中,class priority_queue 定義如下:
namespace std {
template < class T ,
class Container = vector<T> ,
class Compare = less <typename Container::value_type> >
class priority_queue ;
}
由於priority queue需要用到STL heap演算法,所以其內部容器必須支援隨機存取迭代器。例如你可以使用deque來容納元素:
std::priority_queue< float, std::deque<float> > pbuffer ;
核心介面
push() 將一個元素置於priority queue中
top() 返回priority queue中的“下一個元素”
pop() 從priority queue 中移除一個元素
注意:如果priority queue 內沒有元素,執行top()和pop()會導致未定義的行為,應該先採用size()或empty()來檢驗容器是否為空白。
運用執行個體
// 使用VS2008 和 code::blocks 10.05調試通過
#include <iostream>
#include <queue>
using namespace std ;
int main()
{
priority_queue<float> q;
// insert three elements into the priority queue
q.push (66.6);
q.push (22.2);
q.push (44.4);
// read and print two elements
cout << q.top () << ' ';
q.pop ();
cout << q.top () << endl;
q.pop ();
// insert three more elements
q.push (11.1);
q.push (55.5);
q.push (33.3);
// skip one element
q.pop ();
// pop and print remaining elements
while (!q.empty ()) {
cout << q.top () << ' ';
q.pop ();
}
cout << endl ;
}
參考資料 《C++標準程式庫》侯捷 孟岩譯