...

/

Use the Spaceship Operator <=> for Three-Way Comparisons

Use the Spaceship Operator <=> for Three-Way Comparisons

Learn to use the spaceship operator <=> for three-way comparisons.

We'll cover the following...

The three-way comparison operator (<=>), commonly called the spaceship operator because it looks like a flying saucer in profile, is new in C++20. You may wonder, what's wrong with the existing six comparison operators? Nothing at all, and we will continue using them. The purpose of the spaceship is to provide a unified comparison operator for objects.

The common two-way comparison operators return one of two states, true or false, according to the result of the comparison. For example:

const int a = 7;
const int b = 42;
static_assert(a < b);

The a < b expression uses the less-than comparison operator (<) to test if a is less than b. The comparison operator returns true if the condition is satisfied or false if not.

In this case, it returns true because 77 is less than ...