我的操作员<出了什么问题?
What is wrong with my Operator <?
我得到一个关于我的 Vec2 运算符<的断言失败,我不知道出了什么问题。>
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);
}
谢谢
问题是这个运算符不满足弱排序。例如,考虑两点
( 2, 1 )和 ( 1, 2 )
(2, 1) 小于 (1, 2),因为第二个值 1 小于 2。
同时 (1, 2) 也小于 (2, 1),因为第一个值 1 小于第一个值 2。
查看如何为标准类 std::p air 定义此运算符并使用相同的运算符。
满足排序的正确方法是:
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) ;
}
通常,对于这样的比较,您希望比较第一对项目,然后当且仅当它们相等时,比较第二对(依此类推)。
if (x < v.x)
return true;
if (x > v.x)
return false;
return y < v.y;
operator <
应该满足严格的弱排序。
完成这项工作的简短方法:
bool Vec2::operator< (const Vec2& v) const
{
return std::tie(x, y) < std::tie(v.x, v.y);
}
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 格式说明符C++有什么问题
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 我的堆栈和库存清单程序的结构有什么问题?
- 此工厂功能有什么问题?
- 以下 C++ 代码有什么问题?
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- reinterpret_cast,只读访问,简单的可复制类型,会出什么问题?
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了