Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to find the biggest key in a std::map?

Tags:

c++

map

stl

At the moment my solution is to iterate through the map to solve this.

I see there is a upper_bound method which can make this loop faster, but is there a quicker or more succinct way?

like image 958
gak Avatar asked Nov 02 '09 09:11

gak


People also ask

How do I find the key of a map in 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 ...

Can you get the size of a map C++?

map::size() function is an inbuilt function in C++ STL, which is defined in header file. size() is used to check the size of the map container. This function gives size or we can say gives us the number of elements in the map container associated.

What is the complexity of std::map :: insert () method?

Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.


1 Answers

The end:

m.rbegin(); 

Maps (and sets) are sorted, so the first element is the smallest, and the last element is the largest. By default maps use std::less, but you can switch the comparer and this would of course change the position of the largest element. (For example, using std::greater would place it at begin().

Keep in mind rbegin returns an iterator. To get the actual key, use m.rbegin()->first. You might wrap it up into a function for clarity, though I"m not sure if it's worth it:

template <typename T> inline const typename T::key_type& last_key(const T& pMap) {     return pMap.rbegin()->first; }  typedef std::map</* types */> map_type;  map_type myMap; // populate  map_type::key_type k = last_key(myMap); 
like image 141
GManNickG Avatar answered Oct 17 '22 03:10

GManNickG