I am trying to understand the concept of iterator invalidation in vectors. From some of the reading I have done I have found that if a vector contains say 7 elements and you delete the element on the 5th index then the iterators from 5th element onwards become invalidated. This is because all the elements after the 5th index would need to move up one slot. This makes sense to me however I am a bit confused between the following two cases
std::vector<foo> vec {foo{1},foo{2}}; //foo is a simple class
foo* ptr = &vec[0]; //Case 1
std::vector<foo>::iterator it = vec.begin() + 1; //Case 2
Is it safe to say that for a STL container if an iterator becomes invalidated then a pointer becomes invalidated too ? For instance if it
becomes invalidated will ptr
be invalid too ? If not could you give a case in which an iterator becomes invalidated but a pointer remains valid ? I am currently interested in vectors , maps and deques.
Update: So I wrote a little code and experimented
std::vector<foo> vec {foo{1},foo{2},foo{3}};
foo* ptr = &vec[1];
std::vector<foo>::iterator it = vec.begin() + 1;
std::cout << "Before : " << ptr->a << "\n";
vec.erase(vec.begin() + 1); //Remove the second element
std::cout << "Iterator value : " << it->a << "\n";
std::cout << "After : " << ptr->a << "\n";
The result was
Before : 2
Iterator value : 3
After : 3
I am surprised why the vector did not mention that the iterator was invalid since this was the iterator obtained before an element was removed.