讲一下优先队列的用法,其实我就想用两种,至于重载运行符<则不是我想了解的。第一种是直接用默认的:priority_queue<int> Q; 这里表示优先队列Q里面的int型的数的优先级是根据数的值的大小。值越大,优先级越高。
第二种是自己写一个比较函数:
priority_queue<type,container,functional> Q;
type表示要进行比较的数据的类型,container则表示保存这个数据的容器,而functional则表示比较函数。
对于比较函数可以这样定义:
struct cmp
{
bool operator()(type a,type b)
{
..........;这里面的比较的方式与sort当中的比较函数写法一样,不过排序方式就有点不用。
}
对于自定义数据类型,要给出大小关系,即重载”<“ 运算符。
struct node{
int x,y,step;
bool operator <(const node &b) const
{
return step>b.step;
}
friend bool operator<(node a,node b)
{
return a.step>b.step;
}
};
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct point
{
int x,y,z;
char a[100];
friend bool operator <(point a,point b)
{
if(a.y!=b.y)
return a.y>b.y;
return a.x>b.x;
}
};
int main()
{
int m,n,i,j=1;
priority_queue<point>q;
point next;
char b[100];
while(scanf("%s",b)!=EOF)
{
if(strcmp(b,"GET")==0)
{
if(q.empty())
printf("EMPTY QUEUE!\n");
else
{ next=q.top();
q.pop();
printf("%s %d\n",next.a,next.z);
}
}
else
{
scanf("%s%d%d",next.a,&next.z,&next.y);
next.x=j;
j++;
q.push(next);
}
}
return 0;
}