STL默认的比较函数
greater是升序排列,后面的大于前面的
less是降序排列,后面的小于前面的
在初始化优先级队列时默认是less
priority_queue<int,vector<int>,less<int> > que与priority_queue<int > que是一样的效果
也可以自己写比较函数
struct cmp{
bool operator() ( int a , int b ){
return a< b; //与greater是等价的
}
};
priority_queue<int,vector<int>,cmp > p;
另外特别是在结构不是基本结构的比较时,最好自己写比较函数,比较速度能够提高不少
#include<iostream>
#include<string>
#include<queue>
#include<time.h>
#include<algorithm>
#include <functional>
using namespace std;
typedef pair<int,int>int2;
struct cmp{
bool operator() ( int2 a, int2 b ){return a.first< b.first;}
};
int main()
{
//priority_queue<int2,vector<int2>,greater<int2> > p1;
priority_queue<int2,vector<int2>,cmp > p1;
p1.push(int2(1,2));
p1.push(int2(3,4));
p1.push(int2(2,8));
p1.push(int2(5,0));
for(int i=0;i<4;i++)
{
int2 temp=p1.top();p1.pop();
printf("(%d,%d)\n",temp.first,temp.second);
}
system("pause");
return 0;
}