#include<queue>
#include<vector>
#include<iostream>
using namespace std;
struct larger{
bool operator() (int a,int b){
return a>b;
}
};
int main(){
int a[]={0,3,4,2,6,8};
// priority_queue <int ,vector<int>,larger > Q; 1
// priority_queue <int ,vector<int>,greater<int> > Q; 2
// priority_queue <int > Q; 3
for(int i=0;i<5;i++)Q.push(a[i]);
while(!Q.empty())
{
int temp=Q.top();cout<<temp;
Q.pop();}
return 0;
}
//1和3的结果一样,和2的相反
看些更复杂的情况
#include<cstdio>
#include <queue>
using namespace std;
struct Node{
int a;
Node (int a):a(a){}
bool operator < (const Node& n)const{
return a>n.a;
}
};
int main(){
priority_queue<Node> Q;
int a[]={0,3,4,2,6,8};
for(int i=0;i<5;i++)Q.push(Node(a[i]));
while(!Q.empty()){
Node j=Q.top();Q.pop();
printf("%d\n",j.a);
}
return 0;
}
上面的代码输出:0,2,3,4,6
struct Node{
int a;
Node (int a):a(a){}
bool operator < (const Node& n)const{
return a>n.a;
}
};
Node里的operator < (const Node & n)const,两个const都不能少。
在Dev-c中,编译时去掉上面代码中的任何一个const都会使编译器转到stl_function.h的下面这段代码
/// One of the @link comparison_functors comparison functors@endlink.
template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; }
};
从operator()(const _Tp& __x, const _Tp& __y) const看出,
第一个const代表在函数体内,实参不能变,第二个const表示在该函数里面,结构体的成员变量不能被改变。
所以这个函数在调用时,也要遵循上述原则,加上两个const。
如果不加,就会Error
丢掉第一个const 时:no match for 'operator<'(operator types are 'const Node' and 'const Node')
丢掉第二个const 时: [Error] passing 'const Node' as 'this' argument of 'bool Node::operator<(const Node&)' discards qualifiers [-fpermissive],意为丢弃了实参类型限定
代码环境:dev-c和cFree的gcc编译器mindw5