Equivalence operator <=>

I recently saw the operator in someone else's code and experienced a culture shock. What is the beast, what does it do, and when to use it?

#include <iostream>
#include <compare>


int main() {
    int a, b = a = 42;

    std::cout << (a <=> b == 0);
}
Author: cpp questions, 2018-12-22

2 answers

Such an operator is known as "spaceship operator " or a spaceship or a three-way comparison operator (as it is officially called), most often I hear the first option. I saw this operator for the first time in Perl and it seemed like it was the first language that used it, after which it began to appear in Ruby, PHP, C++ , etc.

This operator is used to compare two expressions or values. It's very easy to remember how it works: It returns an integer the value is -1, 0, or 1 if a is, respectively, less than, equal to, or greater than b. Everything is simple and obvious, minus means less, 0 means no difference, 1 is more. From the program code side, this is the equivalent of:

if a<b
  return -1
elsif a>b 
  return 1
else
  return 0
end

The set of such return values has been known for a long time, and the strcmp or memcmp function works with about the same success for strings.

It is very convenient to use this operator for implementations of all sorts of sorts, because if you write some function for comparing and sorting a numeric array needs 3 values (greater than, less than, equal to), since the values of bool (0,1) are not enough.

 8
Author: Firepro, 2018-12-22 19:15:38

If you have ever written comparison operators in more or less heavy C++ classes, then you probably noticed that the whole idea of building a comparison system is

 8
Author: ,