
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterator Invalidation in C++
In C++, we have different containers like vector, list, set, map etc. To iterate through these containers, we can use the iterators. We should be careful when we are using iterators in C++. When we are using iterating over a container, then sometimes, it may be invalidated. If the shape, size is changed, then we can face this kind of problems. In the following example, we can identify the problem of invalidation.
Example Code
#include <iostream> #include <vector> using namespace std; int main() { vector <int> vec{11, 55, 110, 155, 220}; for (auto it=vec.begin(); it!=vec.end(); it++) if ((*it) == 110) vec.push_back(89); //inserting a new value while iterating the vector for (auto it=vec.begin();it!=vec.end();it++) cout << (*it) << " "; }
Output
11 55 110 155 220 89 89
In this program we can get different kinds of results. Here the size of the vector is not defined earlier. Some values are provided for initialization. Now while iterating, we are adding one more value. In this case, if the vector has no space, it will create a new memory block at runtime, and all of the items will be copied. But the iterator will be pointed to the previous address. For this it may generate some invalidations.
Let us see some rules for the iterator invalidations.
|
Insertion |
Erasure |
Resizing |
---|---|---|---|
Vector |
All of the iterators, which are pointing an element before the insertion point, are unaffected, but others are invalidated. And if the size of the vector is increased, then all of the iterators are invalidated. |
All of the iterators, and references, which are after the deletion point, are invalidated. |
Same as like insert or erase. |
Deque |
All iterators and the references are invalidated if the inserted item is not inserted at the end of the deque. |
If the items are deleted from any of the position except the end position, then all iterators will be invalidated. |
Same as like insert or erase. |
List |
All iterators and references are unaffected |
Only those iterators, or references, that are pointing to the element which will be erased, are affected. |
Same as like insert or erase. |
Set, map, multiset, multimap |
All iterators and references are unaffected |
Only those iterators, or references, that are pointing to the element which will be erased, are affected. |
---- |