您的位置:首页 > 编程语言 > C语言/C++

C++ greater<int>()和less<int>()

2017-08-11 10:43 369 查看
1.greater和less是头文件<functional>

template <class T> struct greater {
bool operator() (const T& x, const T& y) const {return x>y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};
template <class T> struct less {
bool operator() (const T& x, const T& y) const {return x<y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};

2.在sort()函数中使用greater<>()和less<int>()
#include<iostream>
#include<vector>
#include<iterator>
#include<functional>
#include<algorithm>
using namespace std;

int main()
{
int A[]={1,4,3,7,10};
const int N=sizeof(A)/sizeof(int);
vector<int> vec(A,A+N);
ostream_iterator<int> output(cout," ");
cout<<"Vector vec contains:";
copy(vec.begin(),vec.end(),output);

cout<<"\nAfter greater<int>():";
sort(vec.begin(),vec.end(),greater<int>());//内置类型从大到小
copy(vec.begin(),vec.end(),output);

cout<<"\nAfter less<int>():";
sort(vec.begin(),vec.end(),less<int>()); //内置类型小大到大
copy(vec.begin(),vec.end(),output);

return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: