What happens when you add elements to a data structure such as a vector while iterating over it. Can I not do this?
I tried this and it breaks:
int m
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 v;
for(int i = 0 ; i < 100 ; i++ )
{
std::cout <<"size = "<