三路比较运算符(<=>)简化C++20中类类型的比较,自动推导大小关系并返回std::strong_ordering等类型;基本用法如int比较所示,自定义类可默认生成或手动实现operator<=>,按成员顺序逐个比较;手动实现时可通过if(auto cmp = ...; cmp != 0)优化逻辑;定义<=>后编译器自动生成==、!=、<、<=、>、>=,但建议单独定义operator==以提升性能;整体减少样板代码,提升安全性与简洁性。

在C++20中,三路比较运算符(<=>),也被称为“太空船运算符”(spaceship operator),可以简化类类型的比较操作。它能自动推导出两个对象之间的大小关系,返回一个比较类别类型,比如 std::strong_ordering、std::weak_ordering 或 std::partial_ordering。
三路比较运算符的返回值表示比较结果:
a <=> b 返回负值:a 小于 ba <=> b 返回 0:a 等于 ba <=> b 返回正值:a 大于 b常见使用方式如下:
#include <iostream>
#include <compare>
int main() {
int x = 5, y = 3;
auto result = x <=> y;
if (result > 0) {
std::cout << "x > y\n";
} else if (result < 0) {
std::cout << "x < y\n";
} else {
std::cout << "x == y\n";
}
return 0;
}
对于自定义类,如果所有成员都支持 <=>,可以使用 = default 自动生成比较操作。
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <compare>
struct Point {
int x;
int y;
// 自动生成三路比较
auto operator<=>(const Point&) const = default;
};
int main() {
Point a{1, 2}, b{1, 3};
if (a < b) std::cout << "a < b\n";
if (a <= b) std::cout << "a <= b\n";
if (a != b) std::cout << "a != b\n";
return 0;
}
编译器会逐个成员按声明顺序比较,相当于先比 x,再比 y。
如果需要自定义逻辑,也可以手动实现 operator<=>。
struct Person {
std::string name;
int age;
auto operator<=>(const Person& other) const {
if (auto cmp = name <=> other.name; cmp != 0)
return cmp;
return age <=> other.age;
}
};
上面的例子先比较名字,名字相等时再比较年龄。利用 if (auto cmp = ...; cmp != 0) 可以提前返回非零结果。
C++20 中,只要定义了 operator<=>,编译器就能自动生成 ==、!=、<、<=、>、>= 的行为。
但注意:operator== 不参与三路比较,建议单独定义以提高效率(特别是对容器或字符串)。
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
基本上就这些。三路比较减少了样板代码,让类的比较更简洁安全。只要成员支持比较,用 = default 是最省事的方式。手动实现时注意比较顺序和返回类型即可。不复杂但容易忽略细节。
以上就是c++++怎么使用C++20的三路比较运算符_c++ C++20三路比较运算符使用方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号