How to Find the Maximum Key in a Map in C++?
Last Updated :
04 Mar, 2024
In C++, the Standard Template Library (STL) provides a map container to store elements in a mapped fashion so each element has a key value and a mapped value. In this article, we will see how to find the maximum key in a map in C++.
Example:
Input :
myMap : {{1, 10}, {2, 20}, {4, 12}, {3, 44}}
Output :
Maximum Key : 4
Finding the Biggest Key in a Map in C++
To find the maximum key in a map, we can use the std::map::rbegin() function that returns a reverse iterator pointing to the last element in the map, which is the maximum key because the map in C++ is in increasing order of keys by default.
C++ Program to Find the Largest Key in a Map
The below example demonstrates how we can use the rbegin() function of a map to find the maximum key in a map in C++ STL.
C++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map< int , int > myMap
= { { 1, 10 }, { 2, 20 }, { 4, 12 }, { 3, 44 } };
auto maxElement = myMap.rbegin();
cout << "Maximum key in the map: " << maxElement->first
<< endl;
return 0;
}
|
Output
Maximum key in the map: 4
Time Complexity: O(1), where N is the size of the map.
Auxiliary Space: O(1)
Note: We can also use std::max_element to find the maximum key in a map in C++.
Share your thoughts in the comments
Please Login to comment...