【问题标题】:c++ struct as map key and operator overloadingc ++结构作为映射键和运算符重载
【发布时间】:2020-11-08 22:32:45
【问题描述】:

我正在尝试在地图或集合中跟踪 2d 坐标。

以下代码会导致此错误: 错误 C2678:二进制“

struct Coord_T {
    uint64_t x, y;
    inline bool operator==(const Coord_T& o) { return x == o.x && y == o.y; }
    inline bool operator<(const Coord_T& o) { return x < o.x || (x == o.x && y < o.y); }
    inline bool operator>(const Coord_T& o) { return x > o.x || (x == o.x && y > o.y); }
    inline bool operator!=(const Coord_T& o) { return x != o.x || y != o.y; }
    inline bool operator<=(const Coord_T& o) { return x < o.x || (x == o.x && y <= o.y); }
    inline bool operator>=(const Coord_T& o) { return x > o.x || (x == o.x && y >= o.y); }
};

int main()
{
    Coord_T coord;
    coord.x = 5;
    coord.y = 6;
    std::map<Coord_T, bool> vals;
    vals[coord] = true;
    return 0;
}

我相信我已经添加了结构所需的所有运算符,那么我还能做些什么来完成这项工作?

【问题讨论】:

  • 似乎fine。你用的是什么编译器?你也应该让你所有的运营商const
  • 我正在使用 Visual Studio 社区及其默认的 C++ 编译器

标签: c++ c++11


【解决方案1】:

将运算符重载为 const 函数:

#include <iostream>
#include <map>



struct Coord_T {
    uint64_t x, y; 
    inline bool operator==(const Coord_T& o) const { return x == o.x && y == o.y; }
    inline bool operator<(const Coord_T& o) const { return x < o.x || (x == o.x && y < o.y); }
    inline bool operator>(const Coord_T& o) const { return x > o.x || (x == o.x && y > o.y); }
    inline bool operator!=(const Coord_T& o) const { return x != o.x || y != o.y; }
    inline bool operator<=(const Coord_T& o) const { return x < o.x || (x == o.x && y <= o.y); }
    inline bool operator>=(const Coord_T& o) const { return x > o.x || (x == o.x && y >= o.y); }

};


int main()
{
    Coord_T coord;
    coord.x = 5; 
    coord.y = 6; 
    std::map<Coord_T, bool> vals;
    vals[coord] = true;
    return 0; 
}

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2010-09-13
    • 2012-11-19
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    相关资源
    最近更新 更多