3-way comparison operator (Space Ship Operator) in C++ 20
The three-way comparison operator “<=>” is called a spaceship operator. The spaceship operator determines for two objects A and B whether A < B, A = B, or A > B. The spaceship operator or the compiler can auto-generate it for us. Also, a three-way comparison is a function that will give the entire relationship in one query. Traditionally, strcmp() is such a function. Given two strings it will return an integer where,
- < 0 means the first string is less
- == 0 if both are equal
- > 0 if the first string is greater.
It can give one of the three results, hence it’s a three-way comparison.
Equality Ordering Primary == <=> Secondary != <, >, <=, >=
From the above table, it can be seen that the spaceship operator is a primary operator i.e., it can be reversed and corresponding secondary operators can be written in terms of it.
(A <=> B) < 0 is true if A < B
(A <=> B) > 0 is true if A > B
(A <=> B) == 0 is true if A and B are equal/equivalent.
Below is the implementation of the three-way comparison operator for two float variables:
Below is the implementation of the three-way comparison operator for two vectors:
Note: You should download the adequate latest compiler to run C++ 20.
Needs of Spaceship Operators:
- It’s the common generalization of all other comparison operators (for totally-ordered domains): >, >=, ==, <=, <. Using <=>, every operation can be implemented in a completely generic way in the case of user-defined data type like a structure where one has to define the other 6 comparison operators one by one instead.
- For strings, it’s equivalent to the old strcmp() function of the C standard library. So it is useful for lexicographic order checks, such as data in vectors, or lists, or other ordered containers.