c++之greater和less在stl中运用

greater< type >()和less< type >()是functional下的两个仿函数,都重载了操作符,它们的源码如下:
greater

/// One of the @link comparison_functors comparison functors@endlink.
  template<typename _Tp>
    struct greater : public binary_function<_Tp, _Tp, bool>
    {
      bool
      operator()(const _Tp& __x, const _Tp& __y) const
      { return __x > __y; }
    };

less

  /// 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; }
    };

可见greater是从大到小排,less是从小到大排。
stl中sort(begin, end),lower_bound( begin,end,num)和upper_bound( begin,end,num)默认的是从小到大排,如果要从大到小排,在最后的参数上写上“greater< int >()”或者写自定义比较函数:

bool cmp(const int& a,const int& b){return a > b;}

greater< int>()表示内置类型从大到小排序,比如说原序列是1,2,4,7,15,34,在greater< int>()的表示下,1>2>4>7>15>34,

优先队列priority_queue< type >和上面的不一样,它的默认的取出顺序是从大到小的,相当于less,从小到大就要写成

priority_queue <int,vector<int>,greater<int> > q;
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值