Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have comparison operators been removed from standard library containers in C++ 20?

I was browsing cppreference and saw that vector's comparison operations have been removed in C++20, and the spaceship operator (<=>) has been introduced. The same thing can be seen for many other standard library containers like set and map.

How do I do the comparisons in the new standard? Also, will C++20 start giving errors on older code?

like image 952
Gaurav Pant Avatar asked Apr 02 '20 19:04

Gaurav Pant


People also ask

What are the new features of C++ 20?

The range-based for loop changed in C++17 to allow the begin() and end() expressions to be of different types and in C++20, an init-statement is introduced for initializing the variables in the loop-scope. It allows us to initialize the container we wish to loop through in the range-declaration itself.

What is the purpose of the comparison operators?

Comparison Operators. Comparison operators compare the contents in a field to either the contents in another field or a constant. They may be used alone or in combination with other operators and functions in both record expressions and target field expressions.


Video Answer


1 Answers

If you continue to browse on the reference site a little, you might come to the section on default comparisons, which simply states that:

In brief, a class that defines operator<=> automatically gets compiler-generated operators <, <=, >, and >=.

So, if the "spaceship" operator exists for a class, the compiler will auto-generate the remaining comparison operators using the result of the <=> operator.

Note that the == operator is not generated (even though it should be possible), but std::vector keeps an overload of operator==.


As for:

will C++ 20 start giving errors on older codes ?

No, it will not.

When you build with a C++20 compiler, the standard library used with it should also be made for C++20 and thus implement the <=> operator, which will then be used as explained above.

However, if you use a C++20 compiler to build with an older standard library, that older standard library will still have the older comparison operators implemented.

like image 75
Some programmer dude Avatar answered Oct 20 '22 04:10

Some programmer dude