C++中的三向比较运算符()怎么用_C++20 "Spaceship Operator" 简化比较操作

c++kquote>三向比较运算符()简化C++类类型比较,支持自动生成或自定义比较逻辑。使用= default可让编译器按成员顺序比较,适用于整数等类型,返回std::strong_ordering;自定义实现时,如按距离比较浮点坐标,应返回std::partial_ordering以处理NaN。相比C++20前需手动重载6个运算符,显著减少代码量并提升安全性,适用于排序与查找场景,关键在于正确选择返回类型。

)怎么用_c++20 \" spaceship operator>

在C++20中,三向比较运算符(),也被称为“Spaceship Operator”,可以大幅简化类类型的比较操作。它能自动推导出两个对象之间的大小关系,减少重复代码。

基本用法

三向比较运算符返回一个std::strong_orderingstd::weak_orderingstd::partial_ordering 类型的值,表示比较结果:

  • std::strong_ordering::equal —— 两者相等
  • std::strong_ordering::less —— 左边小于右边
  • std::strong_ordering::greater —— 左边大于右边

例如,定义一个简单的 Point 类并使用三向比较:

struct Point {
    int x, y;
    auto operator<=>(const Point&) const = default;
};

加上 = default 后,编译器会自动生成比较逻辑:先比较 x,再比较 y。你就可以直接使用 ==!=>>= 进行比较。

自定义比较逻辑

如果需要手动控制比较行为,可以显式实现 。比如让 Point 按照到原点的距离排序:

#include 
#include 

struct Point {
    double x, y;

    std::partial_ordering operator<=>(const Point& other) const {
        double d1 = std::sqrt(x*x + y*y);
        double d2 = std::sqrt(other.x*other.x + other.y*other.y);
        return d1 <=> d2;
    }
};

这里返回 std::partial_ordering 是因为浮点数比较可能产生无序结果(如NaN),而整数通常用 std::strong_ordering

与传统方式对比

在C++20之前,要支持所有比较操作,必须手动重载6个运算符:

bool operator==(const Point& p) const { return x == p.x && y == p.y; }
bool operator!=(const Point& p) const { return !(*this == p); }
bool operator<(const Point& p) const { return x < p.x || (x == p.x && y < p.y); }
// ... 还有 <=, >, >=

现在只需一个 ,其他运算符由编译器自动合成,代码更简洁且不易出错。

基本上就这些。只要合理使用三向比较,就能让自定义类型轻松支持完整的比较操作,尤其是在容器排序或查找时非常实用。不复杂但容易忽略细节,比如返回类型的正确选择。