Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::vector::erase() invalidate the iterator at the point of erase?

C++03 Standard § 23.2.4.3/3 describes std::vector::erase(iterator position) and says specifically

Invalidates all the iterators and references after the point of the erase.

Is the iterator at the point of the erase not invalidated? Specifically if I have a vector with a single element and I copy begin() iterator into a local variable and then call

vec.erase(vec.begin())

Will that iterator I have in a local variable get invalidated or not?

Will the iterators be invalidated after the point of erasure or after and including the point of erasure?

like image 553
sharptooth Avatar asked Sep 16 '14 11:09

sharptooth


People also ask

Is iterator valid after erase?

Every iterator and reference after the point of erasing is invalidated. Only the iterators and references to the erased element is invalidated.

How do you avoid iterator invalidation in C++?

To avoid invalidation of references to elements you can use a std::deque if you do not insert or erase in the middle. To avoid invalidation of iterators you can use a std::list.

Does std :: move invalidate iterators?

No, they should not get invalidated after a move operation.

Does erase change vector capacity?

No. That's implied by the fact that iterators, pointers and references prior to the point of erase remain valid. Reducing the capacity would require a reallocation.


1 Answers

I'd say that your example with erasing the only element in the vector shows that the iterator at the insertion point must be invalidated.

Anyway, in C++11, the wording has been changed (23.3.6.5/3):

Effects: Invalidates iterators and references at or after the point of the erase.

like image 108
Angew is no longer proud of SO Avatar answered Sep 29 '22 18:09

Angew is no longer proud of SO