C++20的三向比较运算符

200 阅读2分钟

C++20中引入了一个全新的运算符,叫做三向比较运算符( Three-way comparison operator ),也被称为 spaceship 运算符。它的主要作用是进行值(value)的比较,可以在比较过程中判断两个值是否相等、大小关系以及大小相等的情况。

语法

三向比较运算符的语法如下:

<=> operator ( const T& a, const T& b);

其中 T 表示进行比较的数据类型, a 和 b 分别表示需要进行比较的两个对象。

返回值

三向比较运算符的返回值类型为一个特殊的类型 std::strong_ordering,它包含三个枚举值:

  • std::strong_ordering::less:如果 a 小于 b,则返回该值;
  • std::strong_ordering::equal:如果 a 等于 b,则返回该值;
  • std::strong_ordering::greater:如果 a 大于 b,则返回该值。

示例

下面展示了使用三向比较运算符对两个整数进行比较的例子:

#include <compare>
#include <iostream>

int main() {
    int a = 1;
    int b = 2;

    std::strong_ordering result = a <=> b;

    if (result == std::strong_ordering::less) {
        std::cout << "a < b" << std::endl;
    } else if (result == std::strong_ordering::equal) {
        std::cout << "a == b" << std::endl;
    } else if (result == std::strong_ordering::greater) {
        std::cout << "a > b" << std::endl;
    }

    return 0;
}

在上面的例子中,我们使用了 <=> 运算符来比较两个整数 a 和 b,然后根据返回值来判断它们的大小关系。

自定义类型

三向比较运算符可以对自定义类型进行比较,只需要在类型中定义 operator<=> 运算符即可。

下面展示了如何在自定义结构体中使用三向比较运算符:

#include <compare>
#include <iostream>

struct Point {
    double x;
    double y;

    auto operator<=>(const Point&) const = default;
};

int main() {
    Point a {1.0, 2.0};
    Point b {2.0, 1.0};

    std::strong_ordering result = a <=> b;

    if (result == std::strong_ordering::less) {
        std::cout << "a < b" << std::endl;
    } else if (result == std::strong_ordering::equal) {
        std::cout << "a == b" << std::endl;
    } else if (result == std::strong_ordering::greater) {
        std::cout << "a > b" << std::endl;
    }

    return 0;
}

上述代码中,我们将自定义结构体 Point 中的 <=> 运算符定义为默认值,这表示使用成员变量自动生成比较函数。对于标准类型(如整型、浮点型等),C++已经为它们定义好了默认的比较行为。用户自定义类型可以通过自定义 operator<=> 运算符来实现自己的比较行为。

总结

三向比较运算符是一个重要的新特性,它可以更加方便地进行值的比较。在实际编程中,我们通常需要对各种数据类型进行比较,三向比较运算符可以帮助我们更轻松地实现这一目的。