特征:就是隊列中最大元素總是在隊首
*優先隊列使用方法
#include<iostream>
#include<queue>
using namespace std;
int main()
{
priority_queue<int> pq;
pq.push(2);
pq.push(0);
pq.push(1);
pq.push(5);
cout<<pq.size()<<endl;
while(pq.empty() != true)
{
cout<<pq.top()<<" ";
pq.pop();
}
cout<<endl;
return 0;
}
*重載"<"操作符來定義優先級
如果優先隊列的元素類型是結構體,可以通過在結構體中重載"<"操作符的方法來修改優先隊列的優先性。
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct Info
{
string name;
float score;
bool operator < (const Info& a)const
{
//由小到大排序
return a.score < score;
}
};
int main()
{
priority_queue<Info> pq;
Info info;
info.name = "CaiCai";
info.score = 68.5;
pq.push(info);
info.name = "Zhejiang";
info.score = 90;
pq.push(info);
info.name = "Ningbo";
info.score = 78.2;
pq.push(info);
while(pq.empty() != true)
{
cout<<pq.top().name<<" : "<<pq.top().score<<endl;
pq.pop();
}
return 0;
}
*重載“()”操作符來定義優先級
如果優先隊列元素不是結構體類型,可以通過重載"()"操作符的方式來定義優先級,當然若元素是結構體類型,也可以通過重載"()"操作符的方式來定義優先級,而不是一定要在結構體内重載"<"操作符。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct cmp
{
bool operator () (const int& a, const int& b)
{
//由小到大
return a < b;
}
};
int main()
{
priority_queue<int, vector<int>, cmp> pq;
pq.push(2);
pq.push(0);
pq.push(1);
pq.push(5);
pq.push(10);
pq.push(23);
while(pq.empty() != true)
{
cout<<pq.top()<<" ";
pq.pop();
}
cout<<endl;
return 0;
}