Expression:invalid comarator怎么办

2023-05-26

这篇文章给大家分享的是有关Expression:invalid comarator怎么办的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

场景

        定义函数如下:

template <class T> struct greaterkey {//用于指定map当中的排序,递减,map中默认递增
 bool operator() (const T& x, const T& y) const
 {
  return x > y;
 }
};
template <class T> struct lesskey {
 bool operator() (const T& x, const T& y) const
 {
  return x < y;
 }
};

解决

vs2010后都是严格比较,相等的两个元素,一定要返回false,可以看到STL的源码:
[cpp]
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);
    <strong>else if (_Pred(_Right, _Left))
        _DEBUG_ERROR2("invalid operator<", _File, _Line);</strong>
    return (true);
    }
如果left和right都一样,STL就会报错。。所以只能修改下自己的代码,当相等的时候,就返回false了

template <class T> struct greaterkey {//用于指定map当中的排序,递减,map中默认递增
 bool operator() (const T& x, const T& y) const
 {

    if (x == y) return false;
      return x > y;
 }
};
template <class T> struct lesskey {
 bool operator() (const T& x, const T& y) const
 {

    if (x == y) return false;

      return x < y;
 }
};

感谢各位的阅读!关于“Expression:invalid comarator怎么办”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

《Expression:invalid comarator怎么办.doc》

下载本文的Word格式文档,以方便收藏与打印。