c++ - 如果您将其用作 Map 中的键,为什么使用不是 const 的操作数<函数定义结构会破坏事物?

标签 c++

我使用 map ,在该 map 中,键的类型是坐标:

struct Coordinates
{
    int x;
    int y;

    Coordinates() 
    {
        x = -1;
        y = -1;
    };
    Coordinates(int a, int b) : x(a), y(b) {};

    bool operator<(const Coordinates& otherCords) const
    {
        int thisSize;
        int otherSize;

        if (x >= y)
        {
            thisSize = x - y;
        }
        else
        {
            thisSize = y - x;
        }

        if (otherCords.x >= otherCords.y)
        {
            otherSize = otherCords.x - otherCords.y;
        }
        else
        {
            otherSize = otherCords.y - otherCords.x;
        }

        return thisSize < otherSize;
    }

};

我花了很长时间才意识到我的操作数函数没有被映射检测到,因为它不是常量。为什么呢?

最佳答案

简短回答:因为这是 map 类的要求。

更长的答案:映射的键是常量并且不能修改(因为这可能会破坏映射所依赖的排序顺序)。由于键是常量值,因此与它们一起使用的任何比较函数都需要是常量。

关于c++ - 如果您将其用作 Map 中的键,为什么使用不是 const 的操作数<函数定义结构会破坏事物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59934183/

相关文章:

继承类的 C++ 奇怪性能

c++ - boost::none_t 实现的基本原理是什么?

c++ - "multiset<int, greater<int>> ms1"和 "multiset<int> ms2(greater<int>())"有什么区别

c++ - 将 unsigned int + 字符串转换为 unsigned char vector

java - 是否有查询 HTML 表的 SQL 包装器

c++ - C++中全局变量和静态成员变量动态初始化的实现

c++ - malloc 和 snprintf 总线核心转储

c++ - Qt:Centos 6.7 session 管理错误和符号查找错误

c++ - 在 C++ 中提高/优化文件写入速度

c++ - vundle 不能与 ftplugin 一起正常工作