erase
invalidates iterator, you have to reconstruct it from return of erase:
it = std::map<int,int>::reverse_iterator(testmap.erase( std::next(it).base() ));
or (c++11)
it = decltype(it){testmap.erase( std::next(it).base() )};
Demo.
For completeness, here is what the corrected loop from the original question looks like (notice that the iterator increment has been removed from the for(...)
:
for (auto rit = testmap.rbegin(); rit != testmap.rend(); /* empty */) {
if (WE_WANT_TO_ERASE(rit)) {
rit = decltype(rit){ testmap.erase(std::next(rit).base()) };
} else {
++rit;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…