When comparing vectors for inequality, use only the equality operator on vector elements. What for?

Both of my compilers (g ++ and clang) will not compile this:

#include <vector> struct A { friend bool operator!=(A const& a1, A const& a2) { return false; } }; int main() { std::vector<A> v1, v2; return (v1 != v2); } 

The error is that !(*__first1 == *__first2) invalid somewhere in stl_algobase.h.

In other words, it completely ignores the existing operator! = Of A Needless to say, if I define operator== , then it compiles and works.

How should it be in accordance with the standard?

If so, why?

+6
source share
1 answer

This is because comparison operators require the type EqualityComparable or LessThanComparable .

Only == and < you can get equivalent != , <= , >= And > . In other words, only using 2 operators can you get all 6 comparisons (assuming I was not mistaken in the logic):

 (a != b) is !(a == b) (a <= b) is !(b < a) (a >= b) is !(a < b) (a > b) is (b < a) 

Standard containers use this normally and will use operator== and operator< when performing type comparisons.

So yes, that is how it should be.

Regarding the second part of the question (why), I'm actually not quite sure why other operators are not used, if available.

+6
source

Source: https://habr.com/ru/post/975588/


All Articles