简体   繁体   English

c++ 结构为 map 键和运算符重载

[英]c++ struct as map key and operator overloading

I am trying to track 2d coordinates in a map or set.我正在尝试在 map 或集合中跟踪二维坐标。

The following code results in this error: error C2678: binary '<': no operator found which takes a left-hand operand of type 'const _Ty' (or there is no acceptable conversion)以下代码导致此错误:错误 C2678:二进制“<”:未找到采用“const _Ty”类型的左侧操作数的运算符(或没有可接受的转换)

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;
}

I believe I've added all the operators I need for the struct, so what else can I do to make this work?我相信我已经添加了结构所需的所有运算符,那么我还能做些什么来完成这项工作?

Overload operators as const functions:将运算符重载为 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; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM