c++中sort函数调用报错Expression : invalid operator <的内部原理

来源:互联网 发布:网络覆盖公司 编辑:程序博客网 时间:2024/05/19 10:35

当我们调用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> inlinebool _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 orderingif (!_Pred(_Left, _Right))return (false);else if (_Pred(_Right, _Left))_DEBUG_ERROR2("invalid operator<", _File, _Line);return (true);}

两次上述检测函数的调用,都会因为_Pre函数(即cmp函数)返回true而调用_DEBUG_ERROR2函数。但是_DEBUG_ERROR2有一个特点:只在第二次被迭代调用时输出错误信息。所以,当第二次反序调用cmp时(即cmp(b,a)),程序会报错:Expression : invalid operator <。

综上所述,cmp函数的改进写法如下

bool cmp(const int &a, const int &b){   if(a!=b)return a<b;      else               return false;}
better version:

bool cmp(const int &a, const int &b){     return a<b;   }




0 0