问题
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.
回答1:
Different containers behave differently when you remove an item.
From http://en.cppreference.com:
std::vector::erase
Invalidates iterators and references at or after the point of the erase, including the
end()
iterator.
std::map::erase
References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
std::deque::erase
All iterators and references are invalidated, unless the erased elements are at the end or the beginning of the container, in which case only the iterators and references to the erased elements are invalidated.
来源:https://stackoverflow.com/questions/32793784/does-a-pointer-become-invalidated-if-an-iterator-is-invalidated-in-stl-container