Open In App

How to Use const_iterator with a Map in C++?

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

In C++, a const_iterator is a type of iterator that points to constant content. This means that using a const_iterator, you can read from but not write to the element it points to. In this article, we will learn how to use a const_iterator with a map in C++ STL.

Example:

Input: 
myMap = {{“apple”, 1}, {“banana”, 2}, {“cherry”, 3}}
Output:
result: {{“apple”, 1}, {“banana”, 2}, {“cherry”, 3}}

Iterator Over a Map Using const_iterator in C++

We can get the const_iterator to a std::map container using the std::map::cbegin() and std::map::cend() functions that return a const_iterator pointing to the beginning and the end of the map, respectively. These constant iterators are recommended when we do not want to modify the data in the map

C++ Program to Iterator Over a Map Using const_iterator

C++




// C++ Program to illustrate how to Iterator Over a Map
// Using const_iterator
#include <iostream>
#include <map>
using namespace std;
  
// Driver Code
int main()
{
    // Creating a map of string and int
    map<string, int> myMap = { { "apple", 1 },
                               { "banana", 2 },
                               { "cherry", 3 } };
  
    // Declaring a const_iterator to the map
    map<string, int>::const_iterator it;
  
    // Displaying map elements using const_iterator
    for (it = myMap.cbegin(); it != myMap.cend(); ++it) {
        cout << it->first << " " << it->second << endl;
    }
  
    return 0;
}


Output

apple 1
banana 2
cherry 3


Time Complexity: O(N), where N is the number of elements in the map.
Space Complexity: O(1)


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

Similar Reads