Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does insertion to STL map invalidate other existing iterator?

Tags:

c++

stl

I used std::map in STL. Can I use iterator after some other element inserted to the map? Is it still valid?

like image 741
Thomson Avatar asked Dec 03 '10 07:12

Thomson


People also ask

What invalidates an iterator?

An Iterator becomes invalidate when the container it points to changes its shape internally i.e. move elements from one location to another and the initial iterator still points to old invalid location. Iterator invalidation in vector happens when, An element is inserted to vector at any location.

What happens to iterator after insert?

For std::vector , all iterators are invalidated after calling insert if it causes the vector's size() to exceed its capacity() (i.e. it must reallocate). Inserting into a vector will change where the end is...

Does std :: move invalidate iterators?

For reference, std::vector::swap does not invalidate iterators.

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.


1 Answers

When in doubt as to the semantics of an operation on a container, consult the documentation:

Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements.

Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased.

This is taken from the SGI STL documentation. While this documentation technically does not specify the behavior of the C++ Standard Library containers, the differences are generally insignificant, aside from the parts of the STL that are not part of the C++ Standard Library, of course.

The SGI STL documentation is an indispensable reference, especially if you don't have a copy of the C++ Standard.

like image 114
James McNellis Avatar answered Sep 22 '22 10:09

James McNellis