Question

I want to erase all the entries except the last two in a map. How could I do that? like the following?

std::map<int, obj>::iterator firstit = mymap.begin();
std::map<int, obj>::iterator lastit = mymap.end();
lastit--;
lastit--;

mymap.erase (firstit ,lastit);
Was it helpful?

Solution

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);

OTHER TIPS

Looks fine to me assuming you do have at least two entries in your map.

--lastit; is sometimes claimed to be more efficient than lastit--; because the latter has to create a temporary iterator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top