博客
关于我
c++之greater和less在stl中运用
阅读量:195 次
发布时间:2019-02-28

本文共 1014 字,大约阅读时间需要 3 分钟。

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

greater

/// One of the @link comparison_functors comparison functors@endlink.  template
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
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 
,greater
> q;

转载地址:http://qrki.baihongyu.com/

你可能感兴趣的文章
nacos注册失败,Feign调用失败,feign无法注入成我们的bean对象
查看>>
nacos源码 nacos注册中心1.4.x 源码 nacos源码如何下载 nacos 客户端源码下载地址 nacos discovery下载地址(一)
查看>>
nacos源码 nacos注册中心1.4.x 源码 spring cloud alibaba 的discovery做了什么 nacos客户端是如何启动的(二)
查看>>
nacos源码 nacos注册中心1.4.x 源码 如何注册服务 发送请求,nacos clinet客户端心跳 nacos 注册中心客户端如何发送的心跳 (三)
查看>>
Nacos源码分析:心跳机制、健康检查、服务发现、AP集群
查看>>