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

可紊 提交于 2019-12-01 03:39:26

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. It's incredibly useful for strings: For that specific case, it's the good old strcmp() from the C standard library. So - useful for anything with lexicographic order, 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".
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!