64,646
社区成员
发帖
与我相关
我的任务
分享
#include <algorithm>
#include <functional>
#include <iostream>
#include <list>
struct Test
{
int priority_;
Test(int prio)
: priority_(prio)
{}
};
// 排序所用
bool Less(const Test *lhs, const Test *rhs)
{
return lhs->priority_ < rhs->priority_;
}
struct FindIf
{
// 在debug、release模式下,才真正用来比较的
bool operator()(const Test *t, int prio) const
{
return prio < t->priority_;
}
// 在debug模式下,需要此重载进行迭代器检测
/*bool operator()(int prio, const Test *t) const
{
return prio < t->priority_;
}*/
// 在debug模式下,需要此重载进行迭代器检测
/*bool operator()(const Test *lhs, const Test *rhs) const
{
return lhs->priority_ < rhs->priority_;
}*/
};
int _tmain(int argc, _TCHAR* argv[])
{
std::list<Test *> queue_;
queue_.push_back(new Test(2));
queue_.push_back(new Test(1));
queue_.push_back(new Test(5));
queue_.push_back(new Test(3));
queue_.push_back(new Test(4));
std::stable_sort(queue_.begin(), queue_.end(), Less);
std::lower_bound(queue_.begin(), queue_.end(), 3, FindIf());
system("pause");
return 0;
}
template<class _FwdIt,
class _Ty,
class _Diff,
class _Pr> inline
_FwdIt _Lower_bound(_FwdIt _First, _FwdIt _Last,
const _Ty& _Val, _Pr _Pred, _Diff *)
{ // find first element not before _Val, using _Pred
_Diff _Count = 0;
_Distance(_First, _Last, _Count);
for (; 0 < _Count; )
{ // divide and conquer, find half that contains answer
_Diff _Count2 = _Count / 2;
_FwdIt _Mid = _First;
_STD advance(_Mid, _Count2);
if (_Pred(*_Mid, _Val))
// if (_DEBUG_LT_PRED(_Pred, *_Mid, _Val))
{ // try top half
_First = ++_Mid;
_Count -= _Count2 + 1;
}
else
_Count = _Count2;
}
return (_First);
}
你看看_Pred怎么调用的就知道为什么这么写了.
struct FindIf
{
bool operator()(const Test *t, int prio) const
{
return prio < t->priority_;
}
};
// TEMPLATE FUNCTION _Debug_lt_pred
template<class _Pr, class _Ty1, class _Ty2> inline
bool _Debug_lt_pred(_Pr _Pred,
const _Ty1& _Left, const _Ty2& _Right,
_Dbfile_t _File, _Dbline_t _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<", _File, _Line);
return (true);
}
上边是追踪宏到最后,意思就是如果在lower_bound里发现ptr()成功,继续宏判断排序是否是一个弱排序,
即如果left==right的情况存在,那么就是一个弱排序,通过if (!_Pred(_Left, _Right))和if (_Pred(_Right, _Left))一起完成了这个判断.
以下是lower_bound的代码:
template<class _FwdIt,
class _Ty,
class _Diff,
class _Pr> inline
_FwdIt _Lower_bound(_FwdIt _First, _FwdIt _Last,
const _Ty& _Val, _Pr _Pred, _Diff *)
{ // find first element not before _Val, using _Pred
_Diff _Count = 0;
_Distance(_First, _Last, _Count);
for (; 0 < _Count; )
{ // divide and conquer, find half that contains answer
_Diff _Count2 = _Count / 2;
_FwdIt _Mid = _First;
_STD advance(_Mid, _Count2);
if (_Pred(*_Mid, _Val))
// if (_DEBUG_LT_PRED(_Pred, *_Mid, _Val))
{ // try top half
_First = ++_Mid;
_Count -= _Count2 + 1;
}
else
_Count = _Count2;
}
return (_First);
}
http://connect.microsoft.com/visualstudio/feedback