zoukankan      html  css  js  c++  java
  • c++中sort函数调用报错Expression : invalid operator <的内部原理

    当我们调用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);
    	}

    两次上述检测函数的调用,都会因为_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;   
    }




  • 相关阅读:
    eclipse中的debug模式的使用
    Hibernate快速入门
    鸟哥的 Linux 私房菜Shell Scripts篇(四)
    Vim命令图解及快捷键讲解
    SpringBoot文档
    鸟哥的 Linux 私房菜Shell Scripts篇(三)
    鸟哥的 Linux 私房菜Shell Scripts篇(二)
    (二)IDEA使用,快捷键
    (一)IDEA使用,基础配置
    idea-git同步服务器代码后撤销操作
  • 原文地址:https://www.cnblogs.com/huoyao/p/4248925.html
Copyright © 2011-2022 走看看