In C++, std::map container store data in the form of key-value pairs where keys are associated with the given value. In this article, we will learn how to access a value in a std::map using key in C++.
Examples
Input: m = {{'a', 11}, {'b', 45}, {'c', 9}}, k = 'c'
Output: 9
Explanation: The key 'c' present in the map with value 9.Input: m = {{'a', 11}, {'b', 45}, {'c', 9}}, k = 'a'
Output: 11
Explanation: The key a present in the map with value 11.
Following are the 3 different methods to access the value of key in std::map in C++:
Table of Content
Using Operator []
The simplest way is to use the [] operator to access the value associated with a key. We pass the key inside the [] brackets and it returns the associated value.
Example
// C++ Program to access the value in a map
// using a key with [] operator
#include <bits/stdc++.h>
using namespace std;
int main() {
map<char, int> m = {{'a', 11}, {'b', 45},
{'c', 9}};
char k = 'c';
// Accessing the value of key in std::map
// using [] operator
cout << m[k];
return 0;
}
Output
9
Time Complexity: O(log n), where n is the number of elements in the map.
Auxiliary Space: O(1)
Note: If the key doesn't exists in the map, then instead of returning an error, this operator will create a new element with the given key and default initialized value.
Using map::at() Method
The std::map::at() method provides a safer method to access to the value associated with a given key in std::map. Unlike [] operator, if the key does not exist, it throws an std::out_of_range exception.
Syntax
m.at(k);
where m is the map and k is the key to be searched.
Example
// C++ Program to illustrate how to access
// a value in std::map using a key with
// std::map::at() method
#include <bits/stdc++.h>
using namespace std;
int main() {
map<char, int> m = {{'a', 11}, {'b', 45},
{'c', 9}, {'d', 21}};
char k = 'c';
// Accessing the value of key in std::map
// using std::map::at()
cout << m.at(k);
return 0;
}
Output
9
Time Complexity: O(log n), where n is the number of elements in the map.
Auxiliary Space: O(1)
Using map::find() Method
We can also access the value of key in std::map using std::map::find() method. This function will return an iterator to the key-value pair if the key present, else returns an iterator pointing to the std::map::end().
Syntax
m.find(k);
where m is the map and k is the key to be searched.
Example
// C++ Program to illustrate how to access
// a value in a map using a key with
// std::map::find() method
#include <bits/stdc++.h>
using namespace std;
int main() {
map<char, int> m = {{'a', 11}, {'b', 45},
{'c', 9}};
char k = 'c';
// Finding the key in std::map
auto it = m.find(k);
// Checking if the key is found
if (it != m.end())
cout << it->second;
else
cout << "Key " << k << " is NOT Present";
return 0;
}
Output
9
Time Complexity: O(log n), where n is the number of elements in the map.
Auxiliary Space: O(1)