The reverse iterator of a std::map.rbegin()
returns the position of the element which contains the largest key_type in a std::map
.
The element with the largest Key can be accessed using the position returned by map.rbegin()
like this:
map.rbegin()->first
However the position returned by map.rbegin()
cannot be used to erase this element.
Why can I access but not erase the same position ?
std::map <unsigned int, std::string> map;
map.emplace(5, "aaa");
map.emplace(7, "bbb");
map.emplace(3, "ccc");
cout << map.rbegin()->first << " : " << map.rbegin()->second << endl; //Reverse iterator works for accessing the element
map.erase(map.rbegin()); //Erase the largest element in the map - Error C2664 converting argument 1 from 'std::reverse_iterator<std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>>' to 'std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>'
map.erase(std::prev(map.end())); //Erase the largest element in the map - WORKS
map.erase(std::prev(map.rbegin().base())); //Erase the largest element in the map - WORKS
It seems logical to me that if a function/method needs an iterator to obtain only one position, then it should not matter what kind of iterator it is.
Things would be different if that iterator described something else than just one position (e.g. direction, too...)
NOTE: I did not ask "How to call erase with a reverse iterator?", I provided a solution to this operation in the last line of my code.
I am asking why I cannot erase with a reverse iterator. i.e. why doesn't the STL simply cast the std::map::reverse_iterator
to std::map:iterator
if it only needs to use it to obtain the position of one element to be erased.
Because the type of the parameter of
erase
is notreverse_iterator
, butiterator
. Those are different types.Knowing the location of the object in memory (which is what you know when you can access an object) is not generally sufficient to access the data structure that contains the element.