1.優先級隊列簡介
優先級隊列(priority_queue)是一種容器適配器,默認基礎容器爲數組vector,使用時需要包含頭文件<queue>。其內部基於堆結構實現,關於堆結構的介紹可以看這裏。理解了堆之後也就能理解優先級隊列的原理,以及爲什麼使用vector作爲默認基礎容器,不過不了解堆結構也不影響優先級隊列的使用。
優先隊列是0個或多個元素的集合,每個元素都有一個優先權或值,對優先隊列執行的操作有
1) 查找;
2) 插入一個新元素;
3) 刪除.
在最小優先隊列中,最小元素在最前面,可以通過top函數訪問,刪除操作用來刪除該元素(此時內部構造最小堆),刪除元素或插入新元素後同樣保證最小元素在最前面這個特點;對於最大優先隊列,最大元素在最前面,可以通過top函數訪問,刪除操作用來刪除該元素(此時內部構造最大堆)。
2.成員函數
empty | 判斷容器是否爲空 |
size | 返回容器大小 |
top | 返回最前面的元素(即堆頂元素) |
push | 插入元素 |
emplace | 構造並插入元素 |
pop | 刪除最前面元素(即堆頂元素) |
swap | 交換兩個優先級隊列 |
在進行插入刪除等操作時,元素始終保持堆結構。
3.構造函數
#include <iostream> // std::cout
#include <queue> // std::priority_queue
#include <vector> // std::vector
#include <functional> // std::greater
using namespace std;
int main()
{
int myints[] = { 10,60,50,20 };
priority_queue<int> first;//默認構造大頂堆,基礎容器爲vector,相當priority_queue<int, vector<int>, less<int> >
priority_queue<int> second(myints, myints + 4);
cout << second.top() << endl;//此時輸出最大元素60
priority_queue<int, vector<int>, greater<int> >
third(myints, myints + 4);//構造小頂堆
cout << third.top() << endl;//輸出最小元素10
return 0;
}
4.自定義排序
#include <iostream> // std::cout
#include <queue> // std::priority_queue
#include <vector> // std::vector
using namespace std;
class mycomparison
{
bool reverse;//reverse爲ture時構造小頂堆,爲false時構造大頂堆
public:
mycomparison(const bool& revparam = false)
{
reverse = revparam;
}
bool operator() (const int& lhs, const int&rhs) const
{
if (reverse) return (lhs > rhs); //小頂堆
else return (lhs < rhs); //大頂堆
}
};
int main()
{
typedef priority_queue<int, vector<int>, mycomparison> mypq_type;
mypq_type fourth(myints, myints + 4); // 大頂堆
cout << fourth.top() << endl; //輸出最大元素60
//mypq_type fifth(myints, myints + 4, mycomparison(true)); // 小頂堆
//cout << fifth.top() << endl; //輸出最小元素10
return 0;
}