C++中的三向比较运算符()怎么用_C++20 "Spaceship Operator" 简化比较操作
发布时间:2025-11-24 19:34
发布者:网络
浏览次数:
在C++20中,三向比较运算符(),也被称为“Spaceship Operator”,可以大幅简化类类型的比较操作。它能自动推导出两个对象之间的大小关系,减少重复代码。
基本用法
三向比较运算符返回一个std::strong_ordering、std::weak_ordering 或 std::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;
};
加上 后,编译器会自动生成比较逻辑:先比较 x,再比较 y。你就可以直接使用 、!=、、<code>、<code>>、>= 进行比较。
自定义比较逻辑
如果需要手动控制比较行为,可以显式实现 。比如让 Point 按照到原点的距离排序:
美图云修
商业级AI影像处理工具
50
查看详情
#include <compare>
#include <cmath>
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); }
// ... 还有 <=, >, >=
现在只需一个 ,其他运算符由编译器自动合成,代码更简洁且不易出错。
基本上就这些。只要合理使用三向比较,就能让自定义类型轻松支持完整的比较操作,尤其是在容器排序或查找时非常实用。不复杂但容易忽略细节,比如返回类型的正确选择。
以上就是C++中的三向比较运算符()怎么用_C++20 "Spaceship Operator" 简化比较操作的详细内容,更多请关注其它相关文章!
# c++
# 三向比较运算符
# 运算符
# 自定义
# 美图
# 有什么
# 适用于
# 重写
# 怎么做
# 解决方法
# 自动生成
# 配置文件
# 泰安网站建设与运营公司
# 镇江营销推广公司招聘
# 青岛网站推广
# 大塘网站优化推荐
# 淮北精准营销推广
# 廊坊网站建设服务器
# 加盟网站建设
# 南昌搜索的关键词排名
# 厦门pc网站建设合作
# 江门福建网站建设




