I am looking for the highest key value (a defined by the comparison operator) of a std::map.
Is this guaranteed to be
map.rbegin()->first
?
(I am a bit shaky on reverse iterators, and how much freedom there is in the implementation of std::map)
If not, please advise. I cannot change the data structure.
The C++ function std::map::end() returns an iterator which points to past-the-end element in the map. The past-the-end element is the theoretical element that would follow the last element in the map.
map::end() end() function is used to return an iterator pointing to past the last element of the map container. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator.
To check for the existence of a particular key in the map, the standard solution is to use the public member function find() of the ordered or the unordered map container, which returns an iterator to the key-value pair if the specified key is found, or iterator to the end of the container if the specified key is not ...
C++ map find() function is used to find an element with the given key value k. If it finds the element then it returns an iterator pointing to the element. Otherwise, it returns an iterator pointing to the end of the map, i.e., map::end().
Yes. Map is a sorted container, the reverse iterator must return the elements in reverse (i.e. decreasing) order of their keys.
[Edit: as Charles Bailey points out in his answer, your code gives the greatest key if it exists - i.e. if the map is non-empty]
Yes, but remember to check that map.rbegin() != map.rend()
.
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