我正在使用带有 struct
的 STL 贴图一把 key 。这是 map 的定义:
std::map<Coord2<uint8_t>, MapTile> tile_;
struct
的定义:
template <typename T>
struct Coord2
{
T x;
T y;
bool operator<(const Coord2<T> &coord) const { return (x < coord.x || y < coord.y); }
bool operator>(const Coord2<T> &coord) const { return (x > coord.x || y > coord.y); }
}
我会因为比较而遇到 map 问题吗?
最佳答案
这operator<
不适合与 C++ 标准库的关联容器一起使用。
比较器必须提供 strict weak ordering ,你的没有。考虑以下证明其不一致的操作数:
a = { x = 1, y = 0 }
b = { x = 0, y = 1 }
鉴于这些输入,a < b == true
和 b < a == true
,但是b != a
.
这种类型的正确比较可能是:
if (x < coord.x)
return true;
if (coord.x < x)
return false;
return y < coord.y;
(当然可以以更紧凑的方式编写此正确的代码,但是我已经调试了足够多的由错误实现的严格弱顺序引起的错误,我强烈建议在比较中非常明确,以便清楚这是正确的。通过这个实现,很明显我们只比较 y
值如果 x
值比较相等,这正是我们想要的。)
关于c++ - 使用结构作为 STL 映射键的要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10936120/