You need to test that iterator
is valid, if your mymap
has less than 2 elements, your code invokes undefined behavior.
auto it = mymap.begin();
auto size = mymap.size();
if (size > 2)
{
std::advance(it, size - 2);
}
mymap.erase(mymap.begin(), it);