Related Articles

# 3-way comparison operator (Space Ship Operator) in C++ 20

• Difficulty Level : Expert
• Last Updated : 24 Nov, 2020

The three-way comparison operator “<=>” is called a spaceship operator. The spaceship operator determines for two objects A and B whether A < B, A = B, or A > B. The spaceship operator or the compiler can auto-generate it for us. Also, a three-way comparison is a function that will give the entire relationship in one query. Traditionally, strcmp() is such a function. Given two strings it will return an integer where,

• < 0 means the first string is less
• == 0 if both are equal
• > 0 if the first string is greater.

It can give one of the three results, hence it’s a three-way comparison.

From the above table, it can be seen that the spaceship operator is a primary operator i.e., it can be reversed and corresponding secondary operators can be written in terms of it.

(A <=> B) < 0 is true if A < B
(A <=> B) > 0 is true if A > B
(A <=> B) == 0 is true if A and B are equal/equivalent.

Program 1:

Below is the implementation of the three-way comparison operator for two float variables:

## C++

 `// C++ 20 program to illustrate the``// 3 way comparison operator``#include ``using` `namespace` `std;`` ` `// Driver Code``int` `main()``{``    ``float` `A = -0.0;``    ``float` `B = 0.0;`` ` `    ``// Find the value of 3 way comparison``    ``auto` `ans = A <= > B;`` ` `    ``// If ans is less than zero``    ``if` `(ans < 0)``        ``cout << ``"-0 is less than 0"``;`` ` `    ``// If ans is equal to zero``    ``else` `if` `(ans == 0)``        ``cout << ``"-0 and 0 are equal"``;`` ` `    ``// If ans is greater than zero``    ``else` `if` `(ans > 0)``        ``cout << ``"-0 is greater than 0"``;`` ` `    ``return` `0;``}`

Program 2:

Below is the implementation of the three-way comparison operator for two vectors:

## C++

 `// C++ 20 program for the illustration of the``// 3-way comparison operator for 2 vectors``#include ``using` `namespace` `std;`` ` `// Driver Code``int` `main()``{``    ``// Given vectors``    ``vector<``int``> v1{ 3, 6, 9 };``    ``vector<``int``> v2{ 3, 6, 9 };`` ` `    ``auto` `ans2 = v1 <= > v2;`` ` `    ``// If ans is less than zero``    ``if` `(ans2 < 0) {`` ` `        ``cout << ``"v1 < v2"` `<< endl;``    ``}`` ` `    ``// If ans is equal to zero``    ``else` `if` `(ans2 == 0) {`` ` `        ``cout << ``"v1 == v2"` `<< endl;``    ``}`` ` `    ``// If ans is greater than zero``    ``else` `if` `(ans2 > 0) {`` ` `        ``cout << ``"v1 > v2"` `<< endl;``    ``}`` ` `    ``return` `0;``}`