The Wayback Machine - https://web.archive.org/web/20240716111710/https://www.geeksforgeeks.org/3-way-comparison-operator-space-ship-operator-in-c-20/
Open In App

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

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  Equality Ordering
Primary == <=>
Secondary != <, >, <=, >=

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++ program to illustrate the 3 way comparison
// (spaceship) operator
#include <compare>
#include <iostream>
using namespace std;
 
int main()
{
    int x = 10;
    int y = 20;
 
    // saving the result of 3 way comparison operator
    auto res = x <=> y;
 
    // executing statements based on the above comparison
    if (res < 0)
        cout << "Less";
    else if (res > 0)
        cout << "Greater";
    else if (res == 0)
        cout << "Same";
    else
        cout << "Unordered";
   
    return 0;
}


Output

ouptut of program 1

 

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 <bits/stdc++.h>
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;
}


Output

output of program 2

Note: You should download the adequate latest compiler to run C++ 20.

Needs of Spaceship Operators:

  • It’s the common generalization of all other comparison operators (for totally-ordered domains): >, >=, ==, <=, <. Using <=>, every operation can be implemented in a completely generic way in the case of user-defined data type like a structure where one has to define the other 6 comparison operators one by one instead.
  • For strings, it’s equivalent to the old strcmp() function of the C standard library. So it is useful for lexicographic order checks, such as data in vectors, or lists, or other ordered containers.
     


Similar Reads

Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Comparison of Java with other programming languages
Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in ev
4 min read
Comparison of Python with Other Programming Languages
Python is an easily adaptable programming language that offers a lot of features. Its concise syntax and open-source nature promote readability and implementation of programs which makes it the fastest-growing programming language in current times. Python has various other advantages which give it an edge over other popular programming languages su
3 min read
C++ Comparison Operators
Comparison operators are operators used for comparing two elements, these are mostly used with if-else conditions as they return true-false as result. There are mainly 6 Comparison Operators namely: Greater than (&gt;) : this operator checks whether operand1 is greater than operand2. If the result turns out to be true, it returns true or else retur
3 min read
Results of comparison operations in C and C++
In C, data type of result of comparison operations is int. For example, see the following program. C/C++ Code #include&lt;stdio.h&gt; int main() { int x = 10, y = 10; printf(&quot;%d \n&quot;, sizeof(x == y)); printf(&quot;%d \n&quot;, sizeof(x &lt; y)); return 0; } Output4 4 Whereas in C++, type of results of comparison operations is bool. For exa
1 min read
How to check whether a number is in the range[low, high] using one comparison ?
This is simple, but interesting programming puzzle. Given three integers, low, high and x such that high &gt;= low. How to check if x lies in range [low, high] or not using single comparison. For example, if range is [10, 100] and number is 30, then output is true and if the number is 5, then output is false for same range. A simple solution is com
3 min read
Ratio Manipulations in C++ | Set 2 (Comparison)
Prerequisite - Ratio Manipulations in C++ | Set 1(Arithmetic)In C++, the &lt;ratio&gt; header file allows us to manipulate ratios using various inbuilt template alias. The header file was introduced from C++11 onwards. In this article, we will be discussing the Comparison of Ratio Manipulations in C++. The following functions are used: ratio_equalr
4 min read
Comparison of boolean data type in C++ and Java
The Boolean data type is one of the primitive data types in both C++ and Java. Although, it may seem to be the easiest of all the data types, as it can have only two values - true or false, but it surely is a tricky one as there are certain differences in its usage in both Java and C++, which if not taken care, can result in an error. The differenc
5 min read
Case-Insensitive String Comparison in C++
In C++, strings are sequences of characters that are used to store text data which can be in both uppercase and lowercase format. In this article, we will learn how we can compare two case-insensitive strings in C++. Example: Input: string1 = "WELCOME TO GEEKS FOR GEEKS"string2 = "welcome to geeks for geeks"Output:Strings are equalCase-Insensitive
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg