C++20 Three-Way Comparisons

 C++20 Three-Way Comparisons


C++20 introduced a standardized syntax for three-way comparisons using the spaceship operator (<=>). It provides a concise and consistent way to compare objects, allowing for easy implementation of comparison operators. Here's an example demonstrating the usage of three-way comparisons:


#include <iostream>

#include <compare>


class Point {

public:

    int x;

    int y;


    Point(int x, int y) : x(x), y(y) {}


    auto operator<=>(const Point& other) const {

        return std::tie(x, y) <=> std::tie(other.x, other.y);

    }

};


int main() {

    Point p1(2, 3);

    Point p2(4, 1);


    if (p1 < p2) {

        std::cout << "p1 is less than p2" << std::endl;

    } else if (p1 > p2) {

        std::cout << "p1 is greater than p2" << std::endl;

    } else {

        std::cout << "p1 is equal to p2" << std::endl;

    }


    return 0;

}

In the above code, we have a Point class representing a 2D point with x and y coordinates. We define the three-way comparison operator operator<=> using the spaceship operator. The implementation compares the x and y coordinates of two points using std::tie and returns the result.


In the main() function, we create two Point objects, p1 and p2, and compare them using the three-way comparison operator. Depending on the result, we print whether p1 is less than, greater than, or equal to p2.


Three-way comparisons simplify the implementation of comparison operators, especially when dealing with multiple attributes or complex types.


C++ Attributes: Likely and Unlikely:

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...