Open In App

How to Find First Key-Value Pair in a Map in C++?

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

In C++ STL, a map is a container that stores key-value pairs in an ordered or sorted manner. In this article, we will learn how to find the first key-value pair in a Map.

Example:

Input:
myMap = {{1, "C++"}, {2, "Java"}, {3, "Python"}, {4, "JavaScript"}};

Output:
First key-Value Pair : (1, C++)

Getting First Key-Value Pair in a Map

To find the first key-value pair in a C++ map, we can use the std::map::begin() function that returns an iterator pointing to the first element in the map. We can dereference this iterator to access the key and value or we can also use the arrow operator(->) to directly access the key and value.

C++ Program to Find the First Key-Value Pair in a Map C++

The below example demonstrates how we can use the std::map::begin() to find the first key-value pair in a map in C++ STL.

C++




// C++ program to illustrate how to find the first key-value
// pair in a Map
#include <iostream>
#include <map>
  
using namespace std;
  
int main()
{
    // Create a map with integer keys and string values
    map<int, string> myMap = { { 1, "C++" },
                               { 2, "Java" },
                               { 3, "Python" },
                               { 4, "JavaScript" } };
  
    // Using the begin() function to get an iterator to the
    // first element
    auto firstElement = myMap.begin();
  
    // Access the key and value using the iterator
    cout << "First key-Value Pair in a map : {"
         << firstElement->first << ", "
         << firstElement->second << '}' << endl;
  
    return 0;
}


Output

First key-Value Pair in a map : {1, C++}

Time Complexity: O(1)
Auxiliary Space: O(1)


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

Similar Reads