c++ - 如果将其用作 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。为什么呢?
解决方案
简短的回答:因为这是地图类的要求。
更长的答案:地图的键是 const 并且不能修改(因为这可能会破坏地图所依赖的排序顺序)。由于键是常量值,因此与它们一起使用的任何比较函数都必须是常量。
推荐阅读
- php - 删除后的Oracle插入命令给出错误
- apache-kafka - 如何将没有架构的数据发送到 kafka - 融合 jdbc - 接收器使用情况?
- python - 如何在生产环境中运行 Django 频道?
- html - 在 Visual Studio Code 中向 django-html 文件添加格式化程序(美化器)
- pandas - 如何从熊猫的所有行中删除组平均值/最小值/最大值
- flutter - 如何在图像中填充颜色
- javascript - 我可以在不同的 React 组件中调用函数吗?
- html - 如何将 CSP 标头(Content-Security-Policy)添加到 vuejs 应用程序?
- graphql - GraphQL 文档资源管理器未在浏览器 .net core 3.1 中显示
- xamarin.forms - Xamarin Forms - 将 Scope-Injected 服务从 tabbedpageviewmodel 传递到页面的视图模型