How to Access Value in a Map Using Iterator in C++?
Last Updated :
29 Feb, 2024
In C++, a map is a container that stores elements in the form of a key value and a mapped value pair. In this article, we will learn how to access a value in a map using an iterator in C++.
Accessing Value in a Map Using Iterator in C++
To access a value associated with a key in a std::map using an iterator, we can use the std::map::find() function to get an iterator to the element with the specified key. If the key is not found, the function returns an iterator to the end.
C++ Program to Access Value in a Map Using Iterator
C++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int > myMap = { { "apple" , 1 },
{ "banana" , 2 },
{ "cherry" , 3 } };
map<string, int >::iterator it = myMap.find( "banana" );
if (it != myMap.end()) {
cout << "The value of the key 'banana' is "
<< it->second << endl;
}
else {
cout << "The key 'banana' was not found in the map"
<< endl;
}
return 0;
}
|
Output
The value of the key 'banana' is 2
Time Complexity: O(log N), where N is the size of the map.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...