简体   繁体   English

为什么我们需要 C++ 中的 spaceship <=> 运算符?

[英]Why do we need the spaceship <=> operator in C++?

Why do we need such an operator in C++ and how is it useful in modern C++ programming?为什么我们在 C++ 中需要这样的运算符,它在现代 C++ 编程中有何用处? Any real world code examples where this can be applied will help.任何可以应用它的真实世界代码示例都会有所帮助。

This question is geared to understand the practical application in real world without reading wordy proposal from Herb Sutter.这个问题旨在了解现实世界中的实际应用,而无需阅读 Herb Sutter 的冗长提案。 No offense to the proposal though.虽然没有冒犯这个提议。

I'll give you three points of motivation, just off the top of my head:我会给你三点动力,就在我的脑海里:

  1. It's the common generalization of all other comparison operator (for totally-ordered domains): > , >= , == , <= , < .这是所有其他比较运算符(对于全序域)的通用概括: >>===<=< Using <=> (spaceship), you can implement each of these other operations in a completely generic way.使用<=> (宇宙飞船),您可以以完全通用的方式实现这些其他操作中的每一个。
  2. For strings, it's equivalent to the good old strcmp() function from the C standard library.对于字符串,它相当于 C 标准库中的旧strcmp()函数。 So - useful for lexicographic order checks, such as data in vectors or lists or other ordered containers.所以 - 对于字典顺序检查很有用,例如向量或列表或其他有序容器中的数据。
  3. For integral numbers, it's what the hardware does anyway: On x86 or x86_64 Comparing a and b ( CMP RAX, RBX ) is basically like subtracting ( SUB RAX, RBX ) except that RAX doesn't actually change, only the flags are affected, so you can use "jump on equal/not equal/greater than/lesser than/etc."对于整数,这就是硬件所做的:在x86x86_64比较 a 和 b ( CMP RAX, RBX ) 基本上就像减法 ( SUB RAX, RBX ) 除了RAX实际上没有改变,只有标志受到影响,所以你可以使用“在等于/不等于/大于/小于/等上跳转”。 (JE/JNE/JGT/JLT etc.) as the next instruction. (JE/JNE/JGT/JLT 等)作为下一条指令。 CMP should be thought of as a "spaceship compare". CMP应该被认为是“宇宙飞船比较”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM