GeeksforGeeks App
Open App
Browser
Continue

# Iterator Invalidation in C++

When the container to which an Iterator points changes shape internally, i.e. when elements are moved from one position to another, and the initial iterator still points to the old invalid location, then it is called Iterator invalidation. One should be careful while using iterators in C++. When we iterate over our container using iterators then it may happen that the iterator gets invalidated. This may be due to change in the shape and size of the container while iterating.

For example, Iterator invalidation in a vector whenever either, at any point in the vector, an element is inserted or an element from the vector is removed. Let us take an example to understand this,

## CPP

 `// CPP program to demonstrate iterator``// invalidations``#include ``using` `namespace` `std;` `// Driver Code``int` `main()``{` `    ``// Creating a sample vector``    ``vector<``int``> v = { 1, 5, 10, 15, 20 };` `    ``// Changing vector while iterating over it``    ``// (This causes iterator invalidation)``    ``for` `(``auto` `it = v.begin(); it != v.end(); it++)``        ``if` `((*it) == 5)``            ``v.push_back(-1);` `    ``for` `(``auto` `it = v.begin(); it != v.end(); it++)``        ``cout << (*it) << ``" "``;` `    ``return` `0;``}`

Output

`1 5 10 15 20 -1 -1 `

In the above example code, it may happen that when we add an element -1 while iterating the vector, the size of the vector can get more than the maximum size due to which a new memory is allocated to the vector and all elements are copied there. But, our iterator still points to the previous old memory address. So, now we can say that iterator gets invalidated. This is one example of invalidation. Given below are some rules for iterator invalidation.

### Iterator Invalidation Rules:1. Insertion

2. Erasure

3. Resizing

Note: Invalidation of iterator does not always mean that dereferencing such an iterator causes a program to crash. It also includes the possibility that iterator does not point to an element which it is supposed to point.