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.

Example

 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)
         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

(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.)

Updated on: 01-Apr-2020

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements