Skip to content

Instantly share code, notes, and snippets.

@sumanth232
Last active October 30, 2015 11:07
Show Gist options
  • Save sumanth232/47f0eadcb5dbb6ecc369 to your computer and use it in GitHub Desktop.
Save sumanth232/47f0eadcb5dbb6ecc369 to your computer and use it in GitHub Desktop.
Invalidation of iterators after modifying containers
As we are not experts on STL iterators, Never ever modify (insert or remove something) in a data structure when you are traversing a STL container (with iterators). YOU DONT WANT TO WASTE TIME DEBUGGING
We don't want to go into the implementation details about invalidating iterators of various containers in different standards of C++ (03, 11 and more in future)
To just give you a rough idea, to simply put it... as a beginner, let us just remember as - 'Iterator of the modified STL container becomes invalidated - means it becomes invalid, erroneous'.
Actually, it doesn't occur in all cases of modification.
To be more technical and precise :
As per the standard : for STL set
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.
So after erasing , iterator it becomes invalid. So it++ results in undefined behaviour. So what happens after that...even God doesn't know.
To prevent the iterator from being invalid,
This will work:
to_erase_it = it;
it++; // increment it so that, it points to a valid element which is not going to be erased in the next step
myset.erase(to_erase_it);
OR SIMPLY : myset.erase(it++); will be enough
To be on safe side during programming and not waste time debugging, never modify a data structure while iterating it
@sumanth232
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment