How to Use const_iterator with a Map in C++?
Last Updated :
29 Feb, 2024
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++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int > myMap = { { "apple" , 1 },
{ "banana" , 2 },
{ "cherry" , 3 } };
map<string, int >::const_iterator it;
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)
Share your thoughts in the comments
Please Login to comment...