0
0
CppConceptBeginner · 3 min read

Spaceship Operator in C++: What It Is and How It Works

The spaceship operator (<=>) in C++ is a three-way comparison operator introduced in C++20 that returns whether one value is less than, equal to, or greater than another. It simplifies writing comparison functions by combining all comparison logic into one operator.
⚙️

How It Works

The spaceship operator (<=>) compares two values and returns a result that tells if the first value is less than, equal to, or greater than the second. Think of it like a traffic light that signals three states: red for less, yellow for equal, and green for greater.

Instead of writing separate code to check if one value is smaller, equal, or bigger, the spaceship operator does all three checks at once and returns a special type that can be used to decide the order. This makes comparing objects easier and less error-prone.

It works by returning a value of type std::strong_ordering, std::weak_ordering, or std::partial_ordering, depending on the kind of comparison needed. These types let you know the exact relationship between the two values.

💻

Example

This example shows how to use the spaceship operator to compare two integers and print the comparison result.

cpp
#include <iostream>
#include <compare>

int main() {
    int a = 5;
    int b = 10;

    auto result = a <=> b;

    if (result < 0) {
        std::cout << "a is less than b\n";
    } else if (result > 0) {
        std::cout << "a is greater than b\n";
    } else {
        std::cout << "a is equal to b\n";
    }

    return 0;
}
Output
a is less than b
🎯

When to Use

Use the spaceship operator when you want to simplify and unify comparison logic in your code. It is especially useful when defining how custom objects should be ordered or compared, such as sorting a list of objects.

Instead of writing multiple comparison operators (<, >, ==, etc.), you can write one <=> operator and let the compiler generate the rest. This reduces bugs and makes your code cleaner.

Real-world use cases include sorting custom data types, implementing comparison in containers, or anywhere you need consistent and complete ordering.

Key Points

  • The spaceship operator (<=>) performs three-way comparison in one step.
  • Introduced in C++20 to simplify comparison operators.
  • Returns special ordering types like std::strong_ordering.
  • Helps reduce code duplication and errors in comparisons.
  • Works well for custom types and sorting algorithms.

Key Takeaways

The spaceship operator (<=>) combines less, equal, and greater comparisons into one operator.
It returns a special ordering type that indicates the comparison result.
Use it to simplify and unify comparison logic in your classes and functions.
Introduced in C++20, it helps reduce bugs and code duplication.
Ideal for sorting and ordering custom data types.