Invalid iterator in vector

I know that erasing will invalidate the iterators during and after deletion. Consider:

std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int>::iterator it = vec.end() - 1; //last element
vec.erase(vec.begin()); //shift everything one to the left, 'it' should be the new 'end()' ?
std::cout << (it == vec.end()); //not dereferencing 'it', just comparing, UB ?

      

Is this undefined behavior for comparing (not dereferencing) an invalid iterator ( it

in this case)? If not, is it it == vec.end()

guaranteed to keep true?

Edit : From the top answer, this looks like UB, if only it

is the only value . But from What are singular and non-singular values ​​in the context of STL iterators? seems to be it

associated with (or was) with a container, therefore does it

non-singular .

I would appreciate further analysis of this, thanks.

+3


source to share


2 answers


Once your iterator is invalid, UB can even compare it to something else:

[C++14: 24.2.1/10]:

An invalid iterator is an iterator that can be singular.

[C++14: 24.2.1/5]:

[..] The results of most expressions are undefined for singular values; the only exceptions are destroying an iterator that contains a singular value, assigning a non-singular value to an iterator that contains a singular value, and, for satisfying iterators, DefaultConstructible

using the initialized value of the iterator as the source of the copy or move operation. [..]



Note that this means that you also cannot compare the default built iterator with any .end()

.

Contrary to popular belief that "pointers are just memory addresses", these rules are also pretty much true for pointers. Indeed, the rules for iterators are a generalization of the rules for pointers.

+5


source


Formally, any iterator that points to an item on or after the item being erased is invalid. So



  • Yes, it's UB (even though it's a pointer under the hood.)

  • UB again, despite the obvious plausibility.

+1


source







All Articles