Three Way Comparison in C++: What It Is and How It Works
three way comparison in C++ is an operator that compares two values and returns whether one is less, equal, or greater than the other in a single step. Introduced in C++20 as the <=> operator (also called the spaceship operator), it simplifies writing comparison code by combining all comparison results into one operation.How It Works
Imagine you want to compare two numbers to see if one is smaller, equal, or bigger. Normally, you write separate checks for each case. The three way comparison operator <=> does all these checks at once and tells you the result in a single answer.
It returns a special value that shows if the first value is less than, equal to, or greater than the second. This is like a traffic light that can show green, yellow, or red instead of just on or off.
This operator helps programmers write cleaner and shorter code because you don’t need to write many if-else statements for comparisons.
Example
This example shows how to use the three way comparison operator to compare two integers and print the result.
#include <iostream> #include <compare> int main() { int a = 5; int b = 10; auto result = a <=> b; // three way comparison if (result < 0) { std::cout << "a is less than b" << std::endl; } else if (result > 0) { std::cout << "a is greater than b" << std::endl; } else { std::cout << "a is equal to b" << std::endl; } return 0; }
When to Use
Use three way comparison when you want to compare two values and need to know if one is smaller, equal, or larger in a clean and efficient way. It is especially useful when writing sorting functions or any code that needs to order or compare objects.
For example, if you create your own data type and want to define how to compare two objects of that type, implementing the <=> operator makes your code simpler and easier to maintain.
Key Points
- The three way comparison operator
<=>returns a value indicating less, equal, or greater. - It was introduced in C++20 to simplify comparison logic.
- It helps reduce multiple comparison statements into one.
- Works well with built-in types and can be customized for user-defined types.
Key Takeaways
<=> returns less, equal, or greater in one step.