What happens when you add elements to a data structure such as a vector while iterating over it. Can I not to this?
The iterator would become invalid IF the vector resizes itself. So you're safe as long as the vector doesn't resize itself.
I would suggest you to avoid this.
The short explanation why resizing invalidates iterator:
Initially the vector has some capacity (which you can know by calling vector::capacity()
.), and you add elements to it, and when it becomes full, it allocates larger size of memory, copying the elements from the old memory to the newly allocated memory, and then deletes the old memory, and the problem is that iterator still points to the old memory, which has been deallocated. That is how resizing invalidates iterator.
Here is simple demonstration. Just see when the capacity
changes:
std::vector<int> v;
for(int i = 0 ; i < 100 ; i++ )
{
std::cout <<"size = "<<v.size()<<", capacity = "<<v.capacity()<<std::endl;
v.push_back(i);
}
Partial Output:
size = 0, capacity = 0
size = 1, capacity = 1
size = 2, capacity = 2
size = 3, capacity = 4
size = 4, capacity = 4
size = 5, capacity = 8
size = 6, capacity = 8
size = 7, capacity = 8
size = 8, capacity = 8
size = 9, capacity = 16
size = 10, capacity = 16
See the complete output here : http://ideone.com/rQfWe
Note: capacity()
tells the maximum number of elements the vector can contain without allocating new memory, and size()
tells the number of elements the vector currently containing.