STL中优先级队列的模版声明中有三个参数,priority_queue<Type,Container,Functional>,故名思义,Type为数据类型,Container则是必须用数组实现的容器,常见的vector,deque,但不能用List,STL默认的是vector,后面的Functional为比较方式,默认的基本类型为数值大的优先。即首元素是最大值。
那么在解决问题时,有时会用到最小堆,即优先级队列中首元素为最小的元素,对于基本类型,可用STL的仿函数直接拿来用
priority_queue<Type,vector<Type>,greater<Type> > Q;
Type即为基本类型,int,long long,double之类的。
对于结构体呢,我们就需要自定义函数了,类似于qsort中自定义cmp函数。经典题型可参考NYOJ 55
自定义函数既可以重载operator< 函数 也可以自定义函数名。
例子1:重载operator< 实现按x从小到大排序,若x相同,则按照y的大小排序
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
struct Point
{
int x,y;
};
bool operator<(Point a,Point b)
{
if(a.x==b.x) return a.y>b.y;
return a.x>b.x;
}
int main()
{
priority_queue <Point> Q; //只需要带一个参数
Point temp;
for(int i=0;i<5;++i) //输入5个数
{
cin>>temp.x>>temp.y;
Q.push(temp);
}
cout<<"*******************"<<endl;
while(!Q.empty())
{
cout<<Q.top().x<<" "<<Q.top().y<<endl;
Q.pop();
}
system("pause");
return 0;
}
另外一种,可带三个参数,例子如下
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
struct Point
{
int x,y;
};
struct cmp //仿函数
{
bool operator()(Point a,Point b) //这里不是重载了,< 变成()了
{
if(a.x==b.x) return a.y>b.y;
return a.x>b.x;
}
};
int main()
{
priority_queue <Point,vector<Point>,cmp> Q; //三个参数
Point temp;
for(int i=0;i<5;++i)
{
cin>>temp.x>>temp.y;
Q.push(temp);
}
cout<<"*******************"<<endl;
while(!Q.empty())
{
cout<<Q.top().x<<" "<<Q.top().y<<endl;
Q.pop();
}
system("pause");
return 0;
}