Open In App

How to Access Value in a Map Using Iterator in C++?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to access a value in a map using an iterator
  
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Creating a map of string and int
    map<string, int> myMap = { { "apple", 1 },
                               { "banana", 2 },
                               { "cherry", 3 } };
  
    // Getting an iterator to the element with the key
    // "banana"
    map<string, int>::iterator it = myMap.find("banana");
  
    // Checking if the key was found
    if (it != myMap.end()) {
        // Accessing the value using the iterator
        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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads