How do I remove from a map while iterating it? like:
std::map<K, V> map;
for(auto i : map)
if(needs_removing(i))
// remove it from the map
If I use map.erase it will invalidate the iterators
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.
The standard associative-container erase idiom:
Note that we really want an ordinary
forloop here, since we are modifying the container itself. The range-based loop should be strictly reserved for situations where we only care about the elements. The syntax for the RBFL makes this clear by not even exposing the container inside the loop body.Edit. Pre-C++11, you could not erase const-iterators. There you would have to say:
Erasing an element from a container is not at odds with constness of the element. By analogy, it has always been perfectly legitimate to
delete pwherepis a pointer-to-constant. Constness does not constrain lifetime; const values in C++ can still stop existing.