参考博文:https://blog.csdn.net/chijianxingfeng/article/details/8886399
greater与less使用
greater<>与less<>是头文件中定义的两个结构,通过重载()运算符,实现内置类型从大到小或从小到大排列。
定义
// TEMPLATE STRUCT greater
template<class _Ty>
struct greater
: public binary_function<_Ty, _Ty, bool>
{ // functor for operator>
bool operator()(const _Ty& _Left, const _Ty& _Right) const
{ // apply operator> to operands
return (_Left > _Right);
}
};
// TEMPLATE STRUCT less
template<class _Ty>
struct less
: public binary_function<_Ty, _Ty, bool>
{ // functor for operator<
bool operator()(const _Ty& _Left, const _Ty& _Right) const
{ // apply operator< to operands
return (_Left < _Right);
}
};
sort()函数中使用greater()和less()
#include<iostream>
#include<algorithm>//因为用了sort()函数
#include<functional>//因为用了greater<int>()
using namespace std;
int main()
{
int a[]={3,1,4,2,5};
int i;
int len=sizeof(a)/sizeof(int);//这里切记要除以sizeof(int)!
sort(a ,a + len, greater<int>());//内置类型的由大到小排序
for(i=0;i<len;i++)
cout<<a[i]<<" ";
cout<<endl;
sort(a, a + len, less<int>()); //内置类型的由小到大排序
for(i=0;i<len;i++)
cout<<a[i]<<" ";
return 0;
}
set中使用greater<>和less<>
set<int,less<int> > setIntA; //该容器是按升序方式排列元素。
set<int,greater<int> > setIntB; //该容器是按降序方式排列元素。