All Recipes
Home/Three-way Comparison/Three-way Comparison Basics
🚀beginner

Three-way Comparison Basics

Use the spaceship operator for easy comparisons

Example Code

cpp
#include <compare>
#include <iostream>
#include <string>
struct Version {
int major, minor, patch;
// Spaceship operator - generates all comparison operators!
auto operator<=>(const Version&) const = default;
};
struct Point {
double x, y;
// Custom spaceship for specific ordering
auto operator<=>(const Point& other) const {
// Compare by distance from origin
auto dist1 = x*x + y*y;
auto dist2 = other.x*other.x + other.y*other.y;
return dist1 <=> dist2;
}
// Need explicit == when <=> is custom
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
};
int main() {
Version v1{1, 2, 3};
Version v2{1, 2, 4};
Version v3{1, 2, 3};
std::cout << std::boolalpha;
std::cout << "v1 < v2: " << (v1 < v2) << std::endl; // true
std::cout << "v1 == v3: " << (v1 == v3) << std::endl; // true
std::cout << "v2 > v1: " << (v2 > v1) << std::endl; // true
Point p1{3, 4}; // distance = 5
Point p2{6, 8}; // distance = 10
std::cout << "p1 < p2: " << (p1 < p2) << std::endl; // true
return 0;
}

Explanation

The spaceship operator (<=>) enables three-way comparison and can automatically generate all six comparison operators. Using '= default' creates member-wise comparisons.

Key Points

  • 1operator<=> generates <, >, <=, >=, ==, !=
  • 2'= default' for member-wise comparison
  • 3Returns strong_ordering, weak_ordering, or partial_ordering
  • 4Custom <=> requires explicit == operator