7

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?

5
  • It means after erase operation all iterators are invalidated, so including the one you are erasing Commented Sep 16, 2014 at 12:01
  • 1
    "Invalidated" to me implies that the object the iterator/reference refers to is still out there somewhere, you're just not pointing to it correctly anymore. That's what happens after the point of the erasure. At the point of the erasure, the object is just gone. Commented Sep 16, 2014 at 12:06
  • 2
    @Rajesh: I assure you it does not mean that. Commented Sep 16, 2014 at 12:09
  • It means position and anything after it is invalid. Cannot be assumed to be part of the vector anymore, or point to anything valid. Cannot be incremented or decremented Commented Sep 16, 2014 at 12:12
  • @Benjamin, you are right Commented Sep 16, 2014 at 12:21

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The complexity of vector::erase() says: Linear on the number of elements erased (destructions) plus the number of elements after the last element deleted (moving).

It seems to me that it is implemented as a lazy grow/shrink array. The iterator, a pointer to the data, when erased, the following data will copied into its place. And thus the iterator you keep, will point to some data else, provided that the data you erase is not the last one.

In fact, it may depend on implementation. Yet I think a lazy grow/shrink array is the best-fit implementation for vector::erase(). [Since it may depends on implementation, don't count on anything like invalidate...]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.