Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use the three-way comparison operator (<=>) instead of the two-way comparison operators? Does this have an advantage?

#include <compare>
#include <iostream>

int main()
{ 
   auto comp1 = 1.1 <=> 2.2;
   auto comp2 = -1 <=> 1;
   std::cout << typeid(comp1).name()<<"\n"<<typeid(comp2).name();
}

Output:

struct std::partial_ordering
struct std::strong_ordering

I know that if the operands have an integral type, the operator returns a PRvalue of type std::strong_ordering. I also know if the operands have a floating-point type, the operator yields a PRvalue of type std::partial_ordering.

But why should I use a three-way comparison operator instead of two-way operators (==, !=, <, <=, >, >=)? Is there an advantage this gives me?

like image 637
east1000 Avatar asked Apr 27 '21 13:04

east1000


People also ask

What is the === comparison operator used for?

Equal to ( === ) — returns true if the value on the left is equal to the value on the right, otherwise it returns false . Not equal to ( !==

What is three way comparison operator?

The C++20 three-way comparison operator <=> (commonly nicknamed the spaceship operator due to its appearance) compares two items and describes the result. It's called the three-way comparison because there are five possible results: less, equal, equivalent, greater, and unordered.

What type of operator do we use to compare 2 or more variables?

The equality operator (==) is used to compare two values or expressions. It is used to compare numbers, strings, Boolean values, variables, objects, arrays, or functions.


1 Answers

It makes it possible to determine the ordering in one operation.
The other operators require two comparisons.

Summary of the other operators:

  • If a == b is false, you don't know whether a < b or a > b
  • If a != b is true, you don't know whether a < b or a > b
  • If a < b is false, you don't know whether a == b or a > b
  • If a > b is false, you don't know whether a == b or a < b
  • If a <= b is true, you don't know whether a == b or a < b
  • If a >= b is true, you don't know whether a == b or a > b

A neat side effect is that all the other operators can be implemented in terms of <=>, and a compiler can generate them for you.

Another side effect is that people might be confused by the use of <=> as the equivalence arrow in mathematics, which it has been pretty much since typewriters got those three symbols.
(I'm personally pretty miffed by how a <=> b is "truthy" if and only if a and b are not equivalent.)

like image 73
molbdnilo Avatar answered Oct 06 '22 03:10

molbdnilo