C++20 introduces the three-way comparison operator, also known as the spaceship operator (<=>). This operator allows for a single, concise way to compare two objects in terms of their order, making it easier to implement comparison logic.
To use the three-way comparison operator, you simply need to implement the operator in your class and use it in place of traditional comparison operators such as <, >, ==, etc. Here's a simple example:
#include
#include
struct Point {
int x, y;
auto operator<=> (const Point& other) const = default;
};
int main() {
Point p1{1, 2};
Point p2{2, 3};
if (p1 < p2) {
std::cout << "p1 is less than p2" << std::endl;
} else {
std::cout << "p1 is not less than p2" << std::endl;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?