简体   繁体   中英

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::iterator s as well, but for some reason, this functionality was removed too.

What is the motivation behind these restrictions?

erase() now take const_iterator s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM