Pregunta

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);
¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top