How to Access a Value in a Map Using a Key in C++?
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++
// C++ Program to illustrate how to access a value in a map // using a key #include <iostream> #include <map> #include <string> using namespace std; int main() { // map declaration map<string, int > mymap; // mapping strings to integers mymap[ "w3wiki" ] = 1; mymap[ "computer" ] = 2; mymap[ "science" ] = 3; mymap[ "portal" ] = 4; // accessing the value in a map using key 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)
Contact Us