I’m wondering why an erase operation from a map inside a loop according to a predicate keep the iterator in a valide state, but not for a vector
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Vector::eraseinvalidates iterators to all elements after the first element that was erased. This makes sense, as the vector is storing its data in an array. When an element is deleted, all elements after it need to be shifted along, e.g.In the above we have an iterator pointing to the value 5, which we want, however, element 1 gets erased, we would now have:
The iterator is pointing past the end of the array, a problem.
With
std::map, the data is stored in a binary tree, so when an element is erased, the left/right pointers of some of the nodes are modified, but their location in memory isn’t changed. As a result, any existing iterators pointing to elements that havent been erased are still valid.