为什么我们需要飞船< => C ++中的运算符? [英] Why do we need the spaceship <=> operator in C++?

查看:111
本文介绍了为什么我们需要飞船< => C ++中的运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C ++中需要这样的运算符,它在现代C ++编程中有什么用?可以应用此功能的任何现实世界代码示例都将有所帮助.

Why do we need such an operator in C++ and how is it useful in modern C++ programming? Any real world code examples where this can be applied will help.

此问题旨在理解现实世界中的实际应用,而无需阅读Herb Sutter的冗长建议.不过,该提议并不构成冒犯.

This question is geared to understand the practical application in real world without reading wordy proposal from Herb Sutter. No offense to the proposal though.

推荐答案

我会给您三个激励点,就在我的头上:

I'll give you three points of motivation, just off the top of my head:

  1. 这是所有其他比较运算符(对于完全排序的域)的通用概括:>>===<=<.使用<=>(太空飞船),您可以以完全通用的方式实施其他所有操作.
  2. 对于字符串,它等效于C标准库中的旧版strcmp()函数.因此-对于字典顺序检查很有用,例如矢量或列表或其他有序容器中的数据.
  3. 对于整数,无论​​如何,这就是硬件要做的事情:在x86x86_64上,比较a和b(CMP RAX, RBX)基本上像是减去(SUB RAX, RBX),只是RAX并没有实际变化,只有标志会受到影响,因此您可以使用在等于/不等于/大于/小于/等上跳跃". (JE/JNE/JGT/JLT等)作为下一条指令. CMP应该被认为是太空飞船比较".
  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. 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." (JE/JNE/JGT/JLT etc.) as the next instruction. CMP should be thought of as a "spaceship compare".

这篇关于为什么我们需要飞船&lt; =&gt; C ++中的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆