Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not possible to remove elements from a std::map using reverse iterators?

I was looking for the most efficient and expressive way to remove the last element from a std::map. I tried:

#include <map>

int main()
{
    std::map<int, int> m;
    m.insert(std::make_pair(1,1));
    m.erase(m.crbegin());
    return 0;
}

The code does not compile, since std::map::erase can take only std::map::const_iterator.

Moreover, prior to C++11 it could take std::map::iterators as well, but for some reason, this functionality was removed too.

What is the motivation behind these restrictions?

like image 788
Martin Drozdik Avatar asked Aug 08 '26 14:08

Martin Drozdik


1 Answers

erase() now take const_iterators to make const_iterator actually useful. iterator is convertible to const_iterator, so the original functionality is not affected.

reverse_iterator is an iterator adapter; it exposes a .base() member function to get the underlying iterator, which you can pass to the container member functions. That said, crbegin().base() is end(), and passing end() to erase() is UB.

like image 94
T.C. Avatar answered Aug 11 '26 05:08

T.C.