Open In App

How to Find the Maximum Key in a Map in C++?

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++ Program to Find the Maximum Key in a Map
  
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Create a map with integer keys and values
    map<int, int> myMap
        = { { 1, 10 }, { 2, 20 }, { 4, 12 }, { 3, 44 } };
  
    // Use reverse iterators to get the maximum key
    auto maxElement = myMap.rbegin();
  
    // Output the maximum key
    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++.

Article Tags :