How to Access a Value in a Map Using a Key in C++?
Last Updated :
01 Mar, 2024
In C++, maps are associative containers that store elements where each element has a key value and a mapped value. No two mapped values can have the same key values. In this article, we will learn how to access a value in a map using a key in C++ STL.
Example:
Input:
myMap {'a' : 1,' b' : 2, 'c' : 3, 'd' : 4}
key=a
Output:
Value at key a is 1
Get a Value From Map Using a Key in C++
To access a value in a map using its key, we can use the [] array subscript operator of the map container to reference the element mapped to the key value given as the parameter.
C++ Program to Access a Value in a Map Using a Key
The below example demonstrates how to access value in a map in C++:
C++
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<string, int > mymap;
mymap[ "geeksforgeeks" ] = 1;
mymap[ "computer" ] = 2;
mymap[ "science" ] = 3;
mymap[ "portal" ] = 4;
string key = "computer" ;
cout << "Value at Key " << key
<< " is: " << mymap.at( "computer" );
return 0;
}
|
Output
Value at Key computer is: 2
Time Complexity: O(log N)
Auxilliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...