日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

c++ std::priority_queue优先队列

發布時間:2023/11/27 生活经验 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c++ std::priority_queue优先队列 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
template <class T, class Container = vector<T>,class Compare = less<typename Container::value_type> > class priority_queue;

需要頭文件 #include <queue>

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

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

priority_queue<int, vector<int>, greater<int> > q;  // 小頂堆
priority_queue<int, vector<int>, less<int> > q;     // 大頂堆

priority_queue 優先隊列,其底層是用堆來實現的。在優先隊列中,隊首元素一定是當前隊列中優先級最高的那一個。

在優先隊列中,沒有 front() 函數與 back() 函數,而只能通過 top() 函數來訪問隊首元素(也可稱為堆頂元素),也就是優先級最高的元素。

    //下面兩種優先隊列的定義是等價的,默認情況下,是降序priority_queue<int> q;priority_queue<int,vector<int>,less<int> >;//后面有一個空格

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、用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();}
}

運行結果:

2 5
1 3
1 2

優先隊列默認的是從大到小的優先級,但是我們在實際使用的時候,往往需要改變優先級(比如從小到大的排列),這時候就需要改變優先級。

#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
13
2
1

?

總結

以上是生活随笔為你收集整理的c++ std::priority_queue优先队列的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。