C++20 introduced the three-way comparison operator, also known as the “spaceship operator” due to its appearance: <=>
. The purpose is to streamline the process of comparing objects.
The Basics
Below is a simple example that uses this new spaceship operator:
#include <compare>
int main() {
int a = 1;
int b = 2;
auto result = a <=> b;
if (result < 0) {
std::cout << "a is less than b" << std::endl;
} else if (result == 0) {
std::cout << "a is equal to b" << std::endl;
} else { // result > 0
std::cout << "a is greater than b" << std::endl;
}
return 0;
}
Note that the compare
header must be included.
For integral types such as int
, the type of the value returned by the spaceship operator is std::strong_ordering
, which can have one of three values:
std::strong_ordering::less
: If the left operand (a
) is less than the right operand (b
).std::strong_ordering::equal
: Ifa
is equal tob
.std::strong_ordering::greater
: Ifa
is greater thanb
.
For floating-point types such as double
, the spaceship operator returns one of four possible values:
std::partial_ordering::less
: Ifa
is less thanb
.std::partial_ordering::equivalent
: Ifa
is “equivalent” tob
. This is essentially the same as “equal”, but also includes the case of-0 <=> +0
.