詳解c++優(yōu)先隊列priority_queue的用法
既然是隊列那么先要包含頭文件#include <queue>, 他和queue不同的就在于我們可以自定義其中數據的優(yōu)先級, 讓優(yōu)先級高的排在隊列前面,優(yōu)先出隊
優(yōu)先隊列具有隊列的所有特性,包括基本操作,只是在這基礎上添加了內部的一個排序,它本質是一個堆實現(xiàn)的
和隊列基本操作相同:
- top 訪問隊頭元素
- empty 隊列是否為空
- size 返回隊列內元素個數
- push 插入元素到隊尾 (并排序)
- emplace 原地構造一個元素并插入隊列
- pop 彈出隊頭元素
- swap 交換內容
定義:priority_queue<Type, Container, Functional>
Type 就是數據類型,Container 就是容器類型(Container必須是用數組實現(xiàn)的容器,比如vector,deque等等,但不能用 list。STL里面默認用的是vector),Functional 就是比較的方式,當需要用自定義的數據類型時才需要傳入這三個參數,使用基本數據類型時,只需要傳入數據類型,默認是大頂堆
一般是:
//升序隊列 priority_queue <int,vector<int>,greater<int> > q; //降序隊列 priority_queue <int,vector<int>,less<int> >q; //greater和less是std實現(xiàn)的兩個仿函數(就是使一個類的使用看上去像一個函數。其實現(xiàn)就是類中實現(xiàn)一個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;
}
輸出
4 3 2 1 0 0 1 2 3 4 cbd abcd abc
2.pari的比較,先比較第一個元素,第一個相等比較第二個
#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();
}
}
輸出
2 5 1 3 1 2
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(c);
f.push(b);
f.push(a);
while (!f.empty())
{
cout << f.top().x << '\n';
f.pop();
}
}
輸出
3 2 1 3 2 1
以上所述是小編給大家介紹的詳解c++優(yōu)先隊列priority_queue的用法,希望對大家有所幫助。在此也非常感謝大家對腳本之家網站的支持!
相關文章
C++實現(xiàn)LeetCode(211.添加和查找單詞-數據結構設計)
這篇文章主要介紹了C++實現(xiàn)LeetCode(211.添加和查找單詞-數據結構設計),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-08-08

