std::map 键作为具有三个 int 成员的结构
std::map with key as a struct with three int members
我想使用一个包含三个整数成员的结构作为键。如何重载 < 运算符。我知道对于两个成员来说,它可以重载为:
bool operator < (const CacheKey& a, const CacheKey& b) {
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
通用解决方案是:
if (a.x != b.x) return a.x < b.x;
if (a.y != b.y) return a.y < b.y;
// ...
return false;
或:
return std::tie(a.x, a.y) < std::tie(b.x, b.y);
(在这种情况下,您可能希望创建一个 returns 绑定成员的成员函数,以便能够为所有需要的运算符执行类似 a.tie() < b.tie()
的操作。)
或者,在 C++20 中,您可以将以下内容添加到 class 以自动获取所有比较运算符,包括 <
:
auto operator<=>(const CacheKey &) const = default;
最直接的方法是:
class Foo {
friend bool operator<(const Foo&, const Foo&);
int a, b, c;
}
bool operator<(const Foo& lhs, const Foo& rhs) {
return (lhs.a < rhs.a) ||
(lhs.a == rhs.a && lhs.b < rhs.b) ||
(lhs.a == rhs.a && lhs.b == rhs.b && lhs.c < rhs.c);
}
我想使用一个包含三个整数成员的结构作为键。如何重载 < 运算符。我知道对于两个成员来说,它可以重载为:
bool operator < (const CacheKey& a, const CacheKey& b) {
return a.x < b.x || (a.x == b.x && a.y < b.y);
}
通用解决方案是:
if (a.x != b.x) return a.x < b.x;
if (a.y != b.y) return a.y < b.y;
// ...
return false;
或:
return std::tie(a.x, a.y) < std::tie(b.x, b.y);
(在这种情况下,您可能希望创建一个 returns 绑定成员的成员函数,以便能够为所有需要的运算符执行类似 a.tie() < b.tie()
的操作。)
或者,在 C++20 中,您可以将以下内容添加到 class 以自动获取所有比较运算符,包括 <
:
auto operator<=>(const CacheKey &) const = default;
最直接的方法是:
class Foo {
friend bool operator<(const Foo&, const Foo&);
int a, b, c;
}
bool operator<(const Foo& lhs, const Foo& rhs) {
return (lhs.a < rhs.a) ||
(lhs.a == rhs.a && lhs.b < rhs.b) ||
(lhs.a == rhs.a && lhs.b == rhs.b && lhs.c < rhs.c);
}