How to Find First Key-Value Pair in a Map in C++?
Last Updated :
04 Mar, 2024
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++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map< int , string> myMap = { { 1, "C++" },
{ 2, "Java" },
{ 3, "Python" },
{ 4, "JavaScript" } };
auto firstElement = myMap.begin();
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)
Share your thoughts in the comments
Please Login to comment...