您的位置:首页 > 其它

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

2014-05-04 22:12 405 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐