參考博文:https://blog.csdn.net/weixin_36888577/article/details/79937886
最近做到一些使用堆排序的題,因此總結一下priority_queue
優先隊列也是隊列,因此頭文件爲,與queue的不同在於可以定義數據的優先級,在插入數據時會自動排序。
基本操作
- top 訪問隊頭元素
- push 插入元素到隊尾並排序
- pop 彈出隊頭元素
- empty
- size
- emplace 原地構造一個元素並插入隊列
- swap
定義
priority_queue<type,container,functional>
- type 元素的數據類型
- container 必須是用數組實現的容器,比如vector,deque。默認爲vector
- functional 優先級的比較方法。對於內置類型默認爲less(大頂堆)
- 對於內置類型構成的,使用默認比較方式的優先隊列,只需要指定type即可
- 具有所有隊列的特性,只是添加了自動排序。實際用堆來實現
std::string wrds [] {"one", "two", "three", "four"};
std::priority_queue<std::string, std::vector<std::string>, std::greater<std::string>> words(std::begin(wrds), std::end(wrds));
可以用任何容器的迭代器(開始和結束)來初始化優先隊列。這裏使用operator>()對元素對象進行比較,從而排序。
std::vector<int> values{21, 22, 12, 3, 24, 54, 56};
std::priority_queue<int> numbers(std::less<int>(),values);
//使用大括號也可以
std::priority_queue<int> numbers{std::less<int>(),values};
//模板指定了比較方式,構造函數的第一個參數也必須傳入
std::priority_queue<std::string, std::vector<std::string>, std::greater<std::string>> words(std::greater<std::string>(),w);
- 用vector或者deque容器來初始化priority_queue
- 構造函數的第一個參數爲比較函數,第二個參數爲容器。要注意的是,即使模板中已經指定了比較方式,第一個參數也必不可少。
迭代器
priority_queue沒有迭代器。只能用top和pop依次取出元素來遍歷。且如此遍歷會將隊列清空。
內置類型舉例
//升序隊列 (小頂堆)
priority_queue <int,vector<int>,greater<int> > q1;
//降序隊列 (大頂堆)
priority_queue <int,vector<int>,less<int> > q2;
元素類型爲pair
- 當需求爲按元素出現的頻率排序,在構建了記錄出現次數的哈希表以後,希望對出現的次數進行排序,並保持對應關係。此處用priority_queue<pair<T1,T2> >來實現再合適不過
- 比較規則爲:先對first進行比較,若first相等,則比較second
priority_queue<pair<int, int> > q3;
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 (!q3.empty())
{
cout << q3.top().first << " " << q3.top().second << endl;
q3.pop();
}
自定義類型
類內運算符重載
struct test1
{
int x;
test1(int a) {x = a;}
bool operator<(const test1& a) const
{
return x < a.x; //大頂堆 less
}
};
int main() {
test1 a(1);
test1 b(2);
test1 c(3);
priority_queue<test1> test_pq;
test_pq.push(a);
test_pq.push(b);
test_pq.push(c);
while (!test_pq.empty()) {
std::cout<<test_pq.top().x<<std::endl;
test_pq.pop();
}
system("pause");
}
//輸出 3 2 1
類外運算符重載
struct test1
{
int x;
test1(int a) {x = a;}
};
bool operator<(const test1& a,const test1& b)
{
return a.x < b.x; //大頂堆 less
}
重寫仿函數
struct test1
{
int x;
test1(int a) {x = a;}
};
struct func
{
bool operator()(const test1& a,const test1& b)
{
return a.x < b.x; //大頂堆
}
};
int main() {
test1 a(1);
test1 b(2);
test1 c(3);
priority_queue<test1, vector<test1>, func> test_pq; //寫pq模板時調用仿函數
test_pq.push(a);
test_pq.push(b);
test_pq.push(c);
while (!test_pq.empty()) {
std::cout<<test_pq.top().x<<std::endl;
test_pq.pop();
}
system("pause");
}