Thomson
Thomson

Reputation: 21615

Does insertion to STL map invalidate other existing iterator?

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

Upvotes: 42

Views: 16176

Answers (3)

Andreas Brinck
Andreas Brinck

Reputation: 52519

From standard 23.1.2/8

The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

Upvotes: 39

James McNellis
James McNellis

Reputation: 355039

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.

Upvotes: 63

NPE
NPE

Reputation: 500257

Inserting into std::map does not invalidate existing iterators.

Upvotes: 12

Related Questions