優先順序隊列是一種用來維護一組元素構成的組合的資料結構,其中每個元素都有一個關鍵字key,元素之間的比較都是通過key來比較的。優先隊列包括最大優先隊列和最小優先隊列,優先隊列的應用比較廣泛,比如作業系統中的發送器,當一個作業完成後,需要在所有等待調度的作業中選擇一個優先順序最高的作業來執行,並且也可以添加一個新的作業到作業的優先隊列中。其樣本使用如下,注意要引入相應的標頭檔queue。
int main(){ //優先順序隊列 priority_queue<int> p1; //預設情況下是最大值優先隊列 priority_queue<int,vector<int>,less<int>> p2; //自訂的最大值優先順序隊列 priority_queue<int,vector<int>,greater<int>> p3; //自訂的最小值優先順序隊列 //測試資料 int tmp; for (int i = 0; i < 10; ++i) { tmp=rand()/1000000+1; p1.push(tmp); p2.push(tmp); p3.push(tmp); } //輸出效果 while(!p1.empty()){ cout<<p1.top()<<" "; p1.pop(); } cout<<endl; while(!p2.empty()){ cout<<p2.top()<<" "; p2.pop(); } cout<<endl; while(!p3.empty()){ cout<<p3.top()<<" "; p3.pop(); } cout<<endl; return 0;}
對此當優先順序隊列內部的元素複雜的時候,可以作如下案例
//重載優先順序隊列符號class Person{public: Person(int age,string name){ this->name=name; this->age=age; } int getAge(){ return this->age; } string getName(){ return this->name; } bool operator < (const Person &p)const{ return age<p.age; }private: int age; string name;};int main(){ priority_queue<Person> ps; Person p1(11,"張三"); Person p2(14,"李四"); Person p3(12,"王無"); ps.push(p1); ps.push(p2); ps.push(p3); while(!ps.empty()){ Person p=ps.top(); cout<<p.getName()<<"->"<<p.getAge()<<" "; ps.pop(); } cout<<endl; return 0;}
此時要注意的是在重載最大值優先順序隊列的時候,只能重載小於符號(<),如果重載大於符號,則編譯時間會報如下錯誤:
error: no match for 'operator<' (operand types are 'const Person' and 'const Person')
點開錯誤碼會發現以下代碼
template<typename _Tp> struct greater : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x > __y; } }; /// One of the @link comparison_functors comparison functors@endlink. template<typename _Tp> struct less : public binary_function<_Tp, _Tp, bool> { _GLIBCXX14_CONSTEXPR bool operator()(const _Tp& __x, const _Tp& __y) const { return __x < __y; } };
即會發現在less的結構體中並沒有定義">"的運算子所以找不到匹配的運算子從而出錯。此時也可以類比以上的最小值優先隊列可以發現在其中也不能重載最"<"的運算子。