首页 > 解决方案 > 如果将其用作 Map 中的键,为什么使用不是 const 的操作数 < 函数定义结构会破坏事情?

问题描述

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

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

};

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

标签: c++

解决方案


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

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


推荐阅读