如何为排序,查找,set,map提供自定义比较功能

set按照operator<重载操作符比较规则从小到大排序

set<type> setValue;

set<type,less<type> > setValue;


set按照operator<重载操作符比较规则从大到小排序

set<type,greater<type> > setValue;


set按照自定义比较规则从大到小排序

set<type, compareType> setValue;

compareType为实现bool operater(const type& v1, const type& v2)的类。

TODO:程序范例。


map按照operator<重载操作符比较规则从小到大排序

map<keyType, valueType> setValue;

map<keyType, valueType,less<keyType>> setValue;

map按照operator<重载操作符比较规则从大到小排序

map<keyType, valueType,greater<keyType>> setValue;


map按照自定义比较规则从大到小排序

map<keyType, valueType,compareKeyType> setValue;

compareKeyType为实现bool operater(const keyType& v1, const keyType& v2)的类。

TODO:程序范例。


模板函数min按照自定义比较规则返回最小值

template<class T, class Compare>

inline const T& min(const T& a, const T& b, Compare) {

return comp(a, b) ? a : b;

Compare为函数或者仿函数


模板函数max按照自定义比较规则返回最小值

template<class T, class Compare>

inline const T& max(const T& a, const T& b, Compare) {

return comp(b, a) ? a : b;

Compare为函数或者仿函数


模板函数max_element按照operator<重载操作符比较规则返回最大值

template<class _FwdIt> inline
	_FwdIt _Max_element(_FwdIt _First, _FwdIt _Last)
	{	// find largest element, using operator<
	_DEBUG_RANGE(_First, _Last);
	_FwdIt _Found = _First;
	if (_First != _Last)
		for (; ++_First != _Last; )
			if (_DEBUG_LT(*_Found, *_First))
				_Found = _First;
	return (_Found);
	}


模板函数max_element按照自定义比较规则返回最大值

template<class _FwdIt,
	class _Pr> inline
	_FwdIt _Max_element(_FwdIt _First, _FwdIt _Last, _Pr _Pred)
	{	// find largest element, using _Pred
	_DEBUG_RANGE(_First, _Last);
	_DEBUG_POINTER(_Pred);
	_FwdIt _Found = _First;
	if (_First != _Last)
		for (; ++_First != _Last; )
			if (_DEBUG_LT_PRED(_Pred, *_Found, *_First))
				_Found = _First;
	return (_Found);
	}

 #define _DEBUG_LT_PRED(pred, x, y)	_Debug_lt_pred(pred, x, y, __FILEW__, __LINE__)

template<class _Pr, class _Ty1, class _Ty2> inline
	bool __CLRCALL_OR_CDECL _Debug_lt_pred(_Pr _Pred, const _Ty1& _Left, const _Ty2& _Right,
		const wchar_t *_Where, unsigned int _Line)
	{	// test if _Pred(_Left, _Right) and _Pred is strict weak ordering
	if (!_Pred(_Left, _Right))
		return (false);
	else if (_Pred(_Right, _Left))
		_DEBUG_ERROR2("invalid operator<", _Where, _Line);
	return (true);
	}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值