c++優先隊列(priority_queue)用法詳解


原文鏈接:https://blog.csdn.net/weixin_36888577/article/details/79937886

 

普通的隊列是一種先進先出的數據結構,元素在隊列尾追加,而從隊列頭刪除。

在優先隊列中,元素被賦予優先級。當訪問元素時,具有最高優先級的元素最先刪除。優先隊列具有最高級先出 (first in, largest out)的行為特征。

 

首先要包含頭文件#include<queue>, 他和queue不同的就在於我們可以自定義其中數據的優先級, 讓優先級高的排在隊列前面,優先出隊。

優先隊列具有隊列的所有特性,包括隊列的基本操作,只是在這基礎上添加了內部的一個排序,它本質是一個堆實現的。

和隊列基本操作相同:

  • top 訪問隊頭元素
  • empty 隊列是否為空
  • size 返回隊列內元素個數
  • push 插入元素到隊尾 (並排序)
  • emplace 原地構造一個元素並插入隊列
  • pop 彈出隊頭元素
  • swap 交換內容

定義:priority_queue<Type, Container, Functional>
Type 就是數據類型,Container 就是容器類型(Container必須是用數組實現的容器,比如vector,deque等等,但不能用 list。STL里面默認用的是vector),Functional 就是比較的方式。

當需要用自定義的數據類型時才需要傳入這三個參數,使用基本數據類型時,只需要傳入數據類型,默認是大頂堆。
一般是:

1 //升序隊列,小頂堆
2 priority_queue <int,vector<int>,greater<int> > q; 3 //降序隊列,大頂堆
4 priority_queue <int,vector<int>,less<int> >q; 5 
6 //greater和less是std實現的兩個仿函數(就是使一個類的使用看上去像一個函數。其實現就是類中實現一個operator(),這個類就有了類似函數的行為,就是一個仿函數類了)

1、基本類型優先隊列的例子:

#include<iostream> #include <queue>
using namespace std; int main() { //對於基礎類型 默認是大頂堆
    priority_queue<int> a; //等同於 priority_queue<int, vector<int>, less<int> > a; // 這里一定要有空格,不然成了右移運算符↓↓
    priority_queue<int, vector<int>, greater<int> > c;  //這樣就是小頂堆
    priority_queue<string> b; for (int i = 0; i < 5; i++) { a.push(i); c.push(i); } while (!a.empty()) { cout << a.top() << ' '; a.pop(); } cout << endl; while (!c.empty()) { cout << c.top() << ' '; c.pop(); } cout << endl; b.push("abc"); b.push("abcd"); b.push("cbd"); while (!b.empty()) { cout << b.top() << ' '; b.pop(); } cout << endl; return 0; }

運行結果:

2 5
1 3
1 2
請按任意鍵繼續. . .

 

2、用pair做優先隊列元素的例子:

 

規則:pair的比較,先比較第一個元素,第一個相等比較第二個。

 

#include <iostream> #include <queue> #include <vector>
using namespace std; int main() { priority_queue<pair<int, int> > a; pair<int, int> b(1, 2); pair<int, int> c(1, 3); pair<int, int> d(2, 5); a.push(d); a.push(c); a.push(b); while (!a.empty()) { cout << a.top().first << ' ' << a.top().second << '\n'; a.pop(); } }

 

 

3、用自定義類型做優先隊列元素的例子

#include <iostream> #include <queue>
using namespace std; //方法1
struct tmp1 //運算符重載<
{ int x; tmp1(int a) {x = a;} bool operator<(const tmp1& a) const { return x < a.x; //大頂堆
 } }; //方法2
struct tmp2 //重寫仿函數
{ bool operator() (tmp1 a, tmp1 b) { return a.x < b.x; //大頂堆
 } }; int main() { tmp1 a(1); tmp1 b(2); tmp1 c(3); priority_queue<tmp1> d; d.push(b); d.push(c); d.push(a); while (!d.empty()) { cout << d.top().x << '\n'; d.pop(); } cout << endl; priority_queue<tmp1, vector<tmp1>, tmp2> f; f.push(b); f.push(c); f.push(a); while (!f.empty()) { cout << f.top().x << '\n'; f.pop(); } }

 

運行結果:

3
2
1
 
3
2
1 請按任意鍵繼續. . .

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM