【问题标题】:What is wrong with my Operator <?我的运算符 < 有什么问题?
【发布时间】:2014-01-07 00:58:10
【问题描述】:

我的 Vec2 的 Operator

bool Vec2::operator<( const Vec2& v ) const
{
    if(x < v.x)
        return true;
    else
        return y < v.y;
}

无效的运算符

template<class _Pr, class _Ty1, class _Ty2> inline
    bool __CLRCALL_OR_CDECL _Debug_lt_pred(_Pr _Pred, const _Ty1& _Left, const _Ty2& _Right,
        const wchar_t *_Where, unsigned int _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<", _Where, _Line);
    return (true);
    }

谢谢

【问题讨论】:

  • 断言是什么?
  • 无效运算符
  • 使用std::tiestd::make_pair为你做严格的弱排序。

标签: c++ operator-overloading operators


【解决方案1】:

问题是这个运算符不满足弱排序。例如考虑两点

( 2, 1 ) 和 (1, 2 )

( 2, 1 ) 小于 ( 1, 2 ),因为第二个值 1 小于 2。

同时 (1, 2) 也小于 (2, 1) 因为第一个值 1 小于第一个值 2。

查看如何为标准类 std::pair 定义 thsi 运算符并使用相同的运算符。

【讨论】:

    【解决方案2】:

    满足排序的正确方法是:

    bool Vec2::operator<( const Vec2& v ) const
    {
        if(x < v.x)
            return true;
        if(x > v.x)
            return false;
        else        
            return y < v.y;
    }
    

    或者(代码高尔夫模式):

    bool Vec2::operator<( const Vec2& v ) const
    {
        return (x != v.x)? (x < v.x)
                         : (y < v.y) ;
    }
    

    【讨论】:

      【解决方案3】:

      通常对于这样的比较,您要比较第一对项目,然后当且仅当它们相等时,比较第二对(依此类推)。

      if (x < v.x)
          return true;
      if (x > v.x)
          return false;
      return y < v.y;
      

      【讨论】:

        【解决方案4】:

        operator &lt; 应该满足Strict weak ordering

        完成这项工作的捷径:

        bool Vec2::operator< (const Vec2& v) const
        {
            return std::tie(x, y) < std::tie(v.x, v.y);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-05-09
          • 1970-01-01
          • 1970-01-01
          • 2019-05-16
          • 2021-06-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多