Search code examples
c++dictionaryerase

c++ map erase in range


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

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