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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With