priority_queue构造方法备忘

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值