C++20 Three-Way Comparison (`<=>`)

beginner
11 min

C++20 Three-Way Comparison (<=>)

Welcome to our deep dive into the C++20 Three-Way Comparison! This powerful feature will revolutionize your coding experience. Let's embark on this exciting journey together. šŸŽÆ

Understanding Three-Way Comparison

Three-Way Comparison is a new addition in C++20 that provides a more intuitive way to compare values. Instead of the traditional <, <=, >, and >=, we now have a single operator <=>. This operator not only checks for less-than, equal-to, and greater-than but also determines if the two values are equal (by returning 0). šŸ’”

The <=> Operator

The <=> operator compares its operands in a consistent manner, which is key for modern C++ features like std::sort. It returns:

  • Negative value if the left operand is less than the right one
  • Zero if the operands are equal
  • Positive value if the left operand is greater than the right one

Example 1: Basic Three-Way Comparison

Let's see a simple example:

cpp
#include <iostream> int main() { int a = 10, b = 20, c = 10; std::cout << "a <=> b: " << (a <=> b) << std::endl; // Output: 1 std::cout << "a <=> c: " << (a <=> c) << std::endl; // Output: 0 std::cout << "b <=> a: " << (b <=> a) << std::endl; // Output: -1 return 0; }

In the above example, a <=> b returns 1 (positive), indicating that b is greater than a. On the other hand, a <=> c returns 0 (zero), as both a and c are equal.

Example 2: Three-Way Comparison with Custom Classes

Three-Way Comparison can also be used with custom classes. Let's create a Person class and implement the comparison:

cpp
#include <iostream> #include <compare> #include <string> struct Person { std::string name; int age; friend bool operator<(Person const& lhs, Person const& rhs) { if (lhs.age == rhs.age) return lhs.name < rhs.name; return lhs.age < rhs.age; } friend bool operator==(Person const& lhs, Person const& rhs) { return lhs.age == rhs.age && lhs.name == rhs.name; } }; int main() { Person person1{"Alice", 25}, person2{"Bob", 25}, person3{"Carol", 30}; std::cout << "person1 < person2: " << (person1 < person2) << std::endl; // Output: 1 std::cout << "person1 == person3: " << (person1 == person3) << std::endl; // Output: 0 std::cout << "person2 < person3: " << (person2 < person3) << std::endl; // Output: 1 return 0; }

In this example, we've defined < and == operators for the Person class. The < operator checks if the age is different and compares the names, while the == operator checks if both age and name are equal.

Quiz

Quick Quiz
Question 1 of 1

What does the `<=>` operator return when comparing two equal values?


That's it for this lesson on C++20 Three-Way Comparison! You're now one step closer to mastering modern C++. Stay tuned for more exciting topics at CodeYourCraft! šŸ“