[C++] How to find the biggest key in a std::map?
The method 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);
Since the map is just an AVL tree then, it’s sorted in an ascending order. So, the element with largest key is the last element and you can obtain it using one of the following two methods:
1、myMap.rbegin()
largestElement = (myMap.rbegin())-> first; // rbegin(): returns an iterator pointing to the last element
2、--myMap.end()
largestElement = (--myMap.end())->first; // end(): returns an iterator pointing to the theortical element following the last element
int main() {
std::map<int, string> mymap;
mymap[1] = "a";
mymap[2] = "hello";
mymap[3] = "how r you";
mymap[4] = "hi";
for (auto i = mymap.begin(); i != mymap.end(); i++) {
cout << i->first<< " ";
cout << i->second << "\n";
}
cout << "test1\n";
cout << mymap.rbegin()->first<< " ";
cout << mymap.rbegin()->second<< " \n";
cout << "test2\n";
cout << (--mymap.end())->first<< " ";
cout << (--mymap.end())->second<< " \n";
return 0;
}
1 a
2 hello
3 how r you
4 hi
test1
4 hi
test2
4 hi