I believe that it is unspecified behaviour (C++03). std::vector
iterators are random access iterators and the behaviour of ==
is defined in the requirements for forward iterators.
== is an equivalence relation
Note that this is a requirement on a type, so must be applicable (in this case) to any pair of valid (dereferencable or otherwise) std::vector::iterator
s. I believe that this means ==
must give you a true
/false
answer and can't cause UB.
— If a and b are equal, then either a and b are both dereferenceable or else neither is dereferenceable.
Conversely, a dereferenceable iterator cannot compare equal to an iterator that is not dereferenceable.
— If a and b are both dereferenceable, then a == b if and only if *a and *b are the same object.
Note the lack of requirement on whether a == b
for two iterators that aren't dereferenceable. So long as ==
is transitive (if a.end() == b.end()
and b.end() == c.end()
then a.end() == c.end()
), reflexive (a.end() == a.end()
) and symmetric (if a.end() == b.end()
then b.end() == a.end()
) it doesn't matter if some, all or no end()
iterators to different containers compare equal.
Note, also, that this is in contrast to <
. <
is defined in terms of b - a
, where a
and b
are both random access iterators. A pre-condition of performing b - a
is that there must be a Distance
value n
such that a + n == b
which requires a
and b
to be iterators into the same range.