Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing vectors for inequality use only equality operator on the vector elements. Why?

Tags:

c++

c++11

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?

like image 268
Carlo Wood Avatar asked Sep 20 '14 21:09

Carlo Wood


People also ask

How do you compare two vectors for equality?

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.

How do you compare two elements in a vector?

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.

Can we use == in vector?

In case of vectors, the operator “==” is overloaded to find the result quickly.


1 Answers

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.

like image 98
Cornstalks Avatar answered Sep 30 '22 08:09

Cornstalks