by few · 1y ago · 0 comments
// erase
map.erase(2);
// iterate
for (auto &[k,v]: map) {
// do stuff
}
godbolt: https://godbolt.org/z/o8f6zhqxqFor unordered_map (and every hash table in the known universe) erasing anything invalidates all iterators, so you can't iterate while erasing. For std::map, you can if you're very, very careful (erasing invalidates the iterator you're currently on, but if you cache the next iterator, THEN erase the current one, it'll probably work, but be very fiddly). Most languages forbid this entirely: e.g. Rust's ownership model doesn't allow it, Python throws an exception, etc. It's just a very bad idea in general.
for(decltype(cont)::const_iterator it=cont.begin();it!=cont.end();++it){
if(Keep(it.first)){
++it;
}else{
it=cont.erase(it);
}
}
There's an argument to be made that maybe you should do something else, but if you want to do the above, you can!In reality, very few real-life containers can support this pattern, which is why this is a headline case for Rust, because it statically prevents this bug.
But yes, for removal the correct thing is always to use `std::erase_if` (C++) or `retain()` (Rust). For insertions, the only real solution is to build up a separate collection while iterating and then merging it into the original container when done. Yucky, but won't crash.