我使用 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/