c++中提供了比较函数
less<type>() //从小到大排序 <
grater<type>() //从大到小排序 >
less_equal<type>() // <=
gtater_equal<type>()// >=
//这四种函数
set集合默认排序方式 从小到大即less的,我们可以通过创建set的时候指定排序方式
set<int,greater<int>> m_set = { 1, 1, 5, 3, 2, 9, 6, 7, 7 };
for each (auto var in m_set)
{
cout << var << " ";
}
另外如果闲创建的比较繁琐我们可以用typedef来重命名
typedef std::set<int,std::greater<int>> IntSet;
typedef std::set<int,std::less<int>> IntSet;
IntSet my_set
IntSet::iterator ipos;
1、greater、 less
他在头文件<functional>里面,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);
}
};
2、Demo测试
我们一般用sort函数的时候,可以作为函数指针传递下去,不需要单独写比较函数作为函数指针传递给sort函数的第三个参数
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
int nums[] = {5, 3, 1, 2, 4};
int length = sizeof(nums)/sizeof(int);
std::cout << "nums length is " << length << std::endl;
sort(nums, nums + length, greater<int>());
for (int i = 0; i < length; ++i)
{
std::cout << nums[i] << "\t";
}
std::cout << std::endl;
sort(nums, nums + length, less<int>());
for (int i = 0; i < length; ++i)
{
std::cout << nums[i] << "\t";
}
std::cout << std::endl;
return 0;
}
3、运行结果
5 4 3 2 1
1 2 3 4 5
原文链接:https://blog.csdn.net/zy13270867781/article/details/74923931
原文链接: