C++20尝鲜:<=>三路比较运算符(Three-way comparison)

C++20引入的三路比较运算符<=>,又称宇宙飞船运算符,简化了自定义类型比较。它支持与strcmp类似的用法,减少比较函数数量,如在C++17需18个,C++20仅需4个。运算结果可转换为布尔关系,并分为std::partial_ordering、std::weak_ordering和std::strong_ordering三种序关系类别,分别对应偏序、弱序和强序。在处理如浮点数、CaseInsensitiveString等类型时,该运算符尤其有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

三路比较运算符 <=> 也被称为宇宙飞船运算符(spaceship operator)。

三路比较运算符表达式的形式为:

左操作数<=>右操作数

为什么引入

如果项目中使用struct的值用作std::map的key,因此就需要自己实现比较运算符。如果实现得不对(可能会出现自相矛盾,a < b 且 b < a),程序可能会崩溃。

struct Name {
  string first_name;
  string mid_name;
  string last_name;
};
//C++11前
bool operator<(const Name& other) const {
  return first_name<other.first_name
      || first_name == other.first_name && mid_name < other.mid_name
      || first_name == other.first_name && mid_name == other.mid_name && last_name < other.last_name;
}
   //C++11后
bool operator<(const Name& other) const {
  return std::tie(first_name, mid_name, last_name) < 
      std::tie(other.first_name, other.mid_name, other.last_name);
}
//C++20
struct Name {
  string first_name;
  string mid_name;
  string last_name;
  //编译器默认实现,注入语义,强序
  std::strong_ordering operator<=>(const Name&) const = default;
};

在C++17, 需要 18 比较函数:

class CIString {
  string s;
public:
  friend bool operator==(const CIString& a, const CIString& b) {
    return a.s.size() == b.s.size() &&
      ci_compare(a.s.c_str(), b.s.c_str()) == 0;
  }
  friend bool operator< (const CIString& a, const CIString& b) {
    return ci_compare(a.s.c_str(), b.s.c_str()) <  0;
  }
  friend bool operator!=(const CIString& a, const CIString& b) {
    return !(a == b);
  }
  friend bool operator> (const CIString& a, const CIString& b) {
    return b < a;
  }
  friend bool operator>=(const CI
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值