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

1

16

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?

Felix answered 2/4, 2020 at 19:4 Comment(0)
A
23

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.

Aylmer answered 2/4, 2020 at 19:8 Comment(5)
Note that technically it is a small compatibility break. If you used to call operator< directly, then you'll get a compile error. Though really, you just shouldn't be doing that.Technetium
@NicolBolas, can you elaborate that ?Felix
Will I be getting an error on doing v1 < v2 ? Both are vectorsFelix
@GauravPant No, that's going to be okay no matter what version of the standard library you use.Aylmer
@GauravPant if you're doing v1 < v2 you'll be fine. If, for some obscure reason, you're explicitly doing v1.operator<(v2) then you'll encounter an error.Leukorrhea

© 2022 - 2024 — McMap. All rights reserved.