【问题标题】:C++ map sometimes throws invalid operator<C++ map 有时会抛出无效的 operator<
【发布时间】:2015-09-17 04:57:11
【问题描述】:
struct vector_nodes_less
{
    inline bool operator()(const Vector2i& a, const Vector2i& b) const
    {
        if (a.x == b.x && a.y == b.y) return false;
        if (a.x < b.x && a.y < b.y) return true;
        if (a.x > b.x && a.y > b.y) return false;       
        return (a.x < b.x || a.y < b.y);
    }
};

typedef std::map <Vector2i, node*, vector_nodes_less> vector_nodes;

当我使用上述类型进行操作时,它会抛出无效的运算符<.>

当键 (0,0) (0,1) 和我对 (1,0) 向量键执行操作时会发生这种情况。

我知道我需要弱严格的排序,但我的功能应该没问题,不是吗?

任何帮助都会受到欢迎,因为这会减慢我的速度。

问候

山姆

【问题讨论】:

  • 无效运算符是什么意思?
  • 为什么要这样写操作符?你想实现特定的顺序吗?
  • 当我运行程序时它崩溃了——“调试断言失败!” c:\windows\system32\MSCP120D.dll c:\Program Files\Microsoft Visual Studio 12.0\VC\include\xtree line 2010 表达式:无效运算符
  • 除非您指定 less 运算符,否则它不会编译。它需要它,因为我使用一个对象作为键

标签: c++ visual-studio-2013


【解决方案1】:

不允许同时拥有a &lt; bb &lt; a 因此,如果您的运算符为一对元素返回true,它应该以相反的顺序为它们返回false。现在考虑对 (0, 1) 和 (1, 0)

编写运算符(如果您不关心特定顺序)的最简单方法是重用pair的operator&lt;

return std::tie(a.x, a.y) < std::tie(b.x, b.y);

【讨论】:

  • 谢谢你,先生,我是个传奇
猜你喜欢
  • 2013-02-18
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 1970-01-01
  • 2017-05-24
  • 2021-04-21
相关资源
最近更新 更多