Iterator Invalidation in C++ program

In this tutorial, we will be discussing a program to understand iterator invalidation in C++.

While iterating over the elements of a container object, sometimes it can become invalidated if we don’t apply bound checks. This mainly occurs due to the change in the shape and size of the container object.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   //declaring a vector
   vector <int> v{1, 5, 10, 15, 20};
   //changing vector during execution
   //which will cause bound invalidation
   for (auto it=v.begin();it!=v.end();it++)
      if ((*it) == 5)
   for (auto it=v.begin();it!=v.end();it++)
      cout << (*it) << " ";
   return 0;


1 5 10 15 20 -1 -1

(It may also happen that to add the new element, the vector gets copied to a new location with our iterator still pointing to the old one which will then give an error.)