Spaceship Operator
Introduced in C++20.
#include <compare>
struct Vec2 {
int x, y;
std::strong_ordering operator<=>(const Vec2& other) const {
if (auto c = x <=> other.x; c != 0) return c;
return y <=> other.y;
}
bool operator==(const Vec2&) const = default;
};
if c == 0, then it means that they are equal
Before, you had to define
- Define
equality - Define
<
Whereas now, we can make use of the <==> operator.
We have 3 types of ordering:
std::strong_ordering: a true total order.- If
a == b, they’re interchangeable for ordering purposes. - Integers, strings, tuples of strongly-ordered things → usually strong.
- If
std::weak_ordering: still a total order, but allows “equivalent but not equal”.- Classic example: case-insensitive compare where
"a"and"A"sort the same (equivalent) but are not equal. - Also used for things like comparing objects by a key that doesn’t fully determine equality.
- Classic example: case-insensitive compare where
std::partial_ordering: sometimes things are unordered.- Example: floating point because
NaNis unordered w.r.t everything.
- Example: floating point because