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

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

Terminates all iterators and links after the delete point.

Is the iterator at the erase point invalid? In particular, if I have a vector with one element, and I copy the itter begin() to a local variable, and then call

 vec.erase(vec.begin()) 

Will this iterator that I have in the local variable be invalid or not?

Will iterators be invalid after the erase point or after and with the erase point?

+6
source share
2 answers

I would say that your example of deleting a single element in a vector shows that the iterator at the insertion point must be invalid.

In any case, in C ++ 11, the wording (23.3.6.5/3) was changed:

Effects: nullifies iterators and links in place or after the erase point.

+8
source

The complexity of vector::erase() is: Linear in the number of elements to be erased (destruction) plus the number of elements after the last element has been deleted (moving).

It seems to me that it is implemented as a lazy array of growth / contraction. An iterator, a pointer to data, when erased, the following data will be copied to its place. And thus, the iterator that you store will point to some data yet, provided that the data you delete is not the last.

In fact, this may be implementation dependent. However, I think that a lazy increase / compression array is the best option for vector::erase() . [Since this may be implementation dependent, do not rely on something like invalidate ...]

0
source

Source: https://habr.com/ru/post/975351/


All Articles