How to Traverse a Map Using Iterator in C++?
In C++, maps are associative containers that store elements where each element has a key value and a mapped value. An iterator is a pointer-like object that allows traversing through the elements of a container like a map. In this article, we will learn how to traverse a map using an iterator in C++.
Example :
Input: myMap[1] = "One"; myMap[2] = "Two"; myMap[3] = "Three"; myMap[4] = "Four"; Output: Here is the map : { {1, One}, {2, Two}, {3, Three}, {4, Four} }
Traverse a Map Using Iterator in C++
To traverse a std::map using an iterator, we can use the std::map::begin() function to get an iterator pointing to the first element of the map and the std::map::end() function to get an iterator pointing one past the last element of the map. Then we can increment the iterator in a loop to traverse through the elements.
C++ Program to Traverse a Map Using an Iterator
C++
// C++ Program to illustrate how to use iterator to traverse // a map #include <iostream> #include <map> using namespace std; int main() { // Create a map with some key-value pairs map< int , string> myMap; myMap[1] = "One" ; myMap[2] = "Two" ; myMap[3] = "Three" ; myMap[4] = "Four" ; myMap[5] = "Five" ; // Using iterator to traverse the map map< int , string>::iterator it; cout << "Here is the map : {" << endl; // using begin() and end() iterator to iterate // through the map for (it = myMap.begin(); it != myMap.end(); ++it) { cout << " {" << it->first << ", " << it->second << "} " << endl; } cout << '}' << endl; cout << "One full iteration complete." ; return 0; } |
Output
Here is the map : { {1, One} {2, Two} {3, Three} {4, Four} {5, Five} } One full iteration complete.
Time Complexity: O(n), where n is the number of elements in the map.
Auxiliary Space: O(1)
Contact Us