|
|
|
|
|
by tom_
381 days ago
|
|
Iterator-based std::unordered_map::erase and std::map::erase return a new iterator, one past the range erased, specifically so that you can erase while iterating. Along these untested lines: 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! |
|
EDIT: just saw your example and checked cppreference, it says the return value "Iterator following the last removed element" for std::unordered_map. So i think you need to add an `it--` after your erase, otherwise it will "skip over" the next element. Right?
Also just read this little nugget on cppreference for unordered_map::erase:
> Removes specified elements from the container.The order of the remaining elements is preserved. (This makes it possible to erase individual elements while iterating through the container.)
This seems like a crazy guarantee to put in the standard, it must really limit the kinds of hash tables you can make that matches the unordered_map interface.