Open In App

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

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a map is an associative container that stores key-value pairs. In this article, we will learn how to find the minimum key in a map in C++.

Example:

Input: 
myMap= {{10,"apple"},{5,"banana"},{20,"cherry"}};
Output:
Minimum key: 5

Find the Smallest Key in a Map in C++

There is no direct method available in C++ to find the minimum key in a map. We have to iterate the map elements one by one and find the minimum key by comparing them.

C++ Program to Find the Minimum Key in a Map

The below example demonstrates how we can find the smallest key in a given map in C++ STL.

C++




// C++ program to illustrate how to find the minimum key in
// a map
#include <iostream>
#include <map>
  
using namespace std;
  
int main()
{
  
    // creating map
    map<int, string> myMap;
    // inserting key-value pairs in a map
    myMap[10] = "apple";
    myMap[5] = "banana";
    myMap[20] = "cherry";
  
    // Finding the minimum key
    auto minKeyIterator = myMap.begin();
  
    // handle the case when map is empty
    if (minKeyIterator != myMap.end()) {
        // print the minimum key
        cout << "Minimum key: " << minKeyIterator->first
             << endl;
    }
    else {
        cout << "Map is empty!" << endl;
    }
  
    return 0;
}


Output

Minimum key: 5

Time Complexity: O(N), where N is the number of elements in the map.
Auxilliary Space: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads