Reputation: 39
I wrote a code to erase an element from the vector but after erasing using an iterator in a for loop, my program is crashing. Even inserting an element in a vector via an iterator results in the same. Here is the code snippet:
vector<int>v1;
v1.reserve(8);
v1.push_back(10);
v1.push_back(8);
v1.push_back(12);
v1.push_back(3);
v1.push_back(7);
v1.push_back(5);
v1.push_back(17);
v1.push_back(1);
int x=6;
std::vector<int>::iterator get_it;
get_it = v1.begin();
for(;get_it!= v1.end();get_it++)
{
if(*get_it < x)
{
v1.insert(get_it, 6);
}
}
I am just trying to understand the reason behind invalidating the iterator after the erase of an element or an insertion of an element happened in Vector container.
Any explanation please?
Upvotes: 0
Views: 367
Reputation: 409166
A vector allocates memory dynamically. If there's not enough room in the vector, it has to allocate new memory, and copy over the data from the old memory. Iterators a basically pointers into the memory the vector wraps, so if the vector reallocates memory the iterators ("pointers") no longer point to allocated memory, but the old free'd memory.
But that's just one reason. The other is that a vector emulates an array, and like an array the elements in a vector is stored contiguously. If you insert or remove an element in the middle of the vector, all data after the inserted/removed element have to be adjusted and moved to new positions to still keep the elements contiguous. Again, iterators "pointing" to the moved elements will no longer point to the correct location.
Upvotes: 4