C++中的比较函数

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

原文链接:

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值