当我们调用sort函数进行排序时,中的比较函数如果写成如下
bool cmp(const int &a, const int &b)
{
if(a!=b)
return a<b;
else
return true;
}
则在待排序列中如果出现相等元素,则会报错Expression : invalid operator <
原因是,c++编译器检测到调用cmp的参数a==b时,c++编译器会立即用反序参数调用cmp函数,即调用cmp(b,a),来判断cmp函数是否已经执行了严格的弱序规则(a与b相等则位置不被改变)
注意:两次cmp函数的调用后,都会调用内部的严格弱序规则检测函数(源码如下)
template<class _Pr, class _Ty1, class _Ty2> inline
bool _Debug_lt_pred(_Pr _Pred,
_Ty1& _Left, _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);
}
两次上述检测函数的调用