Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last key in a std::map

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.

like image 312
peterchen Avatar asked Nov 14 '08 10:11

peterchen


People also ask

How do I get the last element on a map?

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.

What does map end point to?

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.

How do you check if a key exists in a map C++?

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 ...

How do I get the key back from a map in C++?

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().


Video Answer


2 Answers

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]

like image 88
Steve Jessop Avatar answered Oct 02 '22 14:10

Steve Jessop


Yes, but remember to check that map.rbegin() != map.rend().

like image 41
CB Bailey Avatar answered Oct 02 '22 13:10

CB Bailey