Both my compilers (g++ and clang) won't 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 being that !(*__first1 == *__first2)
somewhere in stl_algobase.h is invalid.
In other words, it is completely ignoring the existing operator!= of A
.
Needless to say that if I define an operator==
then it compiles and works.
Is this how it should be according to the standard?
If so, why?
C++ Vector Library - operator== Function The C++ function std::vector::operator== tests whether two vectors are equal or not. Operator == first checks the size of both container, if sizes are same then it compares elements sequentially and comparison stops at first mismatch.
Comparing two vectors using operator == std::vector provides an equality comparison operator==, it can be used to compare the contents of two vectors. For each element in the vector it will call operator == on the elements for comparisons.
In case of vectors, the operator “==” is overloaded to find the result quickly.
It's because the comparison operators want an EqualityComparable
or LessThanComparable
type.
With only ==
and <
, you can derive equivalent !=
, <=
, >=
, and >
. In other words, by only implementing 2 operators, you can get all 6 comparisons (assuming I haven't made a mistake 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 usually, and will use operator==
and operator<
when doing comparisons for types.
So yes, this is as it should be.
As for the second part of the question (the why), I'm actually not entirely sure why the other operators aren't used if available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With