priority_queue:優先隊列
優先級隊列是一種容器適配器,根據一些嚴格的弱排序標準,專門設計使其第一個元素始終是它包含的最大元素。
此上下文類似於堆,其中可以隨時插入元素,並且只能檢索最大堆元素(優先級隊列中頂部的元素)。
注意事項:
- 優先隊列每次取值只能取得排序後的最大堆元素(或自定義排序後的最大或最小元素
- push() 方法 實質上是先調用了 底層容器對象的 push_back() ,然後在所有元素範圍上調用 push_heap 算法將其重新排序到其在堆中的位置
- pop() 方法實質上是先調用 pop_heap 算法來保持 隊列 的堆屬性,然後調用底層容器對象的成員函數 pop_back 來刪除該元素
常用API 如下:
- empty(): 判斷容器內是否爲空
- size(): 獲取容器大小
- top(): 獲取 堆頂 元素(注意是排序後的元素)
- push() : 插入新元素,注意每次插入都會引發 新排序
- pop() : 刪除 堆頂 元素,刪除的元素是具有最高值的元素,注意每次刪除都會引發新排序
初始化及自定義排序優先隊列
默認大頂堆:
#include <queue>
using namespace std;
priority_queue<int> first;
// 默認 大頂堆,此時爲空隊列
int myints[] = {10,60,50,20};
priority_queue<int> second(myints,myints + 4);
// 大頂堆,將數組 迭代入 隊列中
pair<> 大頂堆:
priority_queue<pair<int,int> > third;
pair<int,int> a(3,4);
pair<int,int> b(3,5);
pair<int,int> c(4,3);
third.push(c);
third.push(b);
third.push(a);
// 大頂堆,先按照 pair 的 first 元素降序,first 元素相等時,再按照 second 元素降序
小頂堆:
#include <queue>
#include <vector>
using namespace std;
priority_queue<int,vector<int>,greater<int>> q;
// 使用 仿函數 greate<> 創建一個 小頂堆
pair<> 小頂堆:
#include <queue>
#include <vector>
using namespace std;
priority_queue < pair < int, int > , vector < pair < int, int >> , greater < pair < int, int >>> p;
// 大=小頂堆,先按照 pair 的 first 元素升序,first 元素相等時,再按照 second 元素升序
相當於將 小頂堆的 int 換成 pair<int,int>
自定義堆:
-
重寫仿函數
struct Node{ int x, y; Node( int a= 0, int b= 0 ): x(a), y(b) {} }; struct cmp{ bool operator() ( Node a, Node b ){ //默認是less函數 //返回true時,a的優先級低於b的優先級(a排在b的後面) if( a.x== b.x ) { return a.y> b.y } return a.x> b.x; } }; priority_queue<Node, vector<Node>, cmp> q; // 自定義堆,隊列中的每一項元素爲 Node 構造體
-
運算符重載
struct Node{ int x, y; Node(int a = 0, int b= 0):x(a), y(b) {} }; bool operator < (const Node& a, const Node& b ){ if (a.x == b.x) return a.y > b.y; return a.x > b.x; } priority_queue<Node> q; // 自定義 小頂堆