Learn How To Iterate Map In C++ With Codes

Iterate Map In C++

In this article, you will learn what C++ maps are and how we can iterate over a map using C++ programming language. We will discuss various methods of iterating through maps in detail and learn about the concept in simple steps.

If you are stuck on more such topics in your C++ assignment and need assistance, you can reach out to us at Codingzap! Our team of skilled programmers will be happy to help you out. But now, let’s get into today’s topic.

Summary Of The Article:

  • A map in C++ is a container that stores data in the form of pairs of keys and values.

  • Unlike sequential iterator containers like string or vector, a map stores keys in increasing order.

  • We can traverse an unordered map as well by using the auto iterator that iterates over keys and value pairs.

What Are Maps In C++? Read Below

You might have heard about dictionaries in Python, Maps in C++ also work similarly. A C++ map is an associative container that is used to store elements in the form of key-value pairs.

In maps, each element is associated with a unique identifier. This unique identifier represents the ‘key’ and the element represents the ‘value’ associated with the key in the pair. Unlike other containers like arrays or vectors, where elements are stored sequentially, maps utilize key-value pairs.

Let’s discuss the key value structure of maps in more detail before we jump in to discuss how to iterate over maps in cpp.

Understand Key-Value Pair Structure Of Maps

As we said above, keys are identifiers that have some values associated with them. In maps, we have unique keys, which means that no two elements can have the same identifier linked to them. C++ maps store the key-value pairs in a balanced binary tree.

A key acts as an index that we can use to retrieve the value of the corresponding data value. Also, two keys cannot have the same values associated with them.

A programmer explaining key-value pair structure of maps

These keys and values are stored in ascending order in the balanced binary tree which makes it efficient for us to perform operations like insertion and deletion. Let’s see how to create a map and insert the key-value pairs in it.

We will also use the same to understand the map iteration process. Have a look at the syntax given below.

				
					std::map <key_datatype, value_datatype> map_name = {{key1, value1}....{key n, value n}};
				
			

To use it in your code, you need to use the <map> header file. Map container is a part of the STL or Standard Template Library in C++, thus, we have used std::map in this case.

The key_datatype and value_datatype can be anything like string, int, float, etc.

Once you have created the map, you can insert the elements in it. There are many operations you can perform on this data. For example – insert elements, erase elements, find a particular key, and more. Let’s take a look at an example and iterate over it!

Basic Map Iteration Using STL Iterator

The Standard Template Library allows us to create an iterator object for maps. We can initialize the iterator to start from the beginning of the map and traverse it till the end. Look at the example code below to understand how its working.

				
					#include <iostream>
#include <map>

int main()
{
    std::cout <<"-----MAP ITERATION--------"<<std::endl;
    // create a map named Student and insert the elements in it
    std::map<std::string, int> Student = {{"Alex", 1}, {"Joe", 2}, {"Charlie",3}};

    // initialise the position of the iterator to the start of the map
    std::map<std::string, int>::iterator it = Student.begin();
    
    // iterate till the end of the map
    while (it != Student.end())
	{   
	    // get key
		std::string name = it->first;
		// get value
		int roll = it->second;
		std::cout << name << " : " << roll << std::endl;
		// iterator incremented to point next item
		it++;
	}
    
    return 0;
}
				
			

Explanation Of The Program:

  • We have created a map named Student that has the names of some students and their roll numbers.

  • We are then creating and initializing an iterator pointing at the beginning called it that will help us traverse it till the end.

  • For every iteration, we are accessing the key and value using the ‘it’ iterator till map end.

Let’s check out the output to see if we have traveled through all elements or not. Look at the image below to get a better idea.

Output:

Iteration Using STL Iterator

Did you face any difficulty understanding the above concept? Don’t worry, you can get help from reliable C++ programming homework expertsย and clear all your doubts.

Range-Based for Loops for Map Iteration

The range-based ‘for’ loop is used for iterating over a map and an unordered map. For this, we use the auto keyword. The code provided below explains the same. Have a look!

				
					#include <iostream>
#include <map>

using namespace std;

int main()
{
 
    int freq[] = {1,2,3,5,6,2,2,1,5};
    int n = sizeof(freq) / sizeof(freq[0]);
    
    // create a map to find element frequency
    map<int, int> elementFreq;
    for (int i = 0; i < n; i++)
        elementFreq[freq[i]]++;
    
    // using auto keyword to iterate and find frequency of each element
    cout << "Element  Frequency" << endl;
    for (auto i : elementFreq)
        cout <<"Frequency of "<< i.first << " is " << i.second << endl;
    
    return 0;
}
				
			

Explanation Of The Program:

  • We have an array of integers named freq having repeating numbers.

  • We will use this as a map by adding all the elements in ‘elementFreq’ map.

  • Using the auto keyword, we will iterate over the map and calculate the element frequency.

The result of the above code is given in the image below. By looking at it we will see that we have successfully performed our task.

Output:

Range-Based for Loops for Map Iteration Output

Many of you may wonder, “Can we iterate in unordered_map C++?” Absolutely!

The above program also works with unordered_map in C++ although the order of each element may be random.

Traverse A Map Using std::for_each And Lambda Function

We can also iterate a map in C++ by using the lambda function and the for_each method. In this case, the lambda function will act as a callback. Let’s see the code given below to understand this.

				
					#include <iostream>
#include <map>
#include <algorithm>
int main()
{
    
    // create a map named Student and insert the elements in it
    std::map<std::string, int> Student = {{"Alex", 1}, {"Joe", 2}, {"Charlie",3}};

    // initialise the position of the iterator to the start
    std::map<std::string, int>::iterator it = Student.begin();
    

    // Iterating over all elements of the map till map end.
    std::for_each(
            Student.begin(), Student.end(),
        [](std::pair<std::string, int> p) {
          
            std::cout << p.first << " has " << p.second
                      <<" Roll No" << std::endl;
        });
    
    return 0;
}
				
			

Explanation Of The Program:

  • We have a map that contains student names and roll numbers as key and value pairs.

  • We are setting an iterator pointing to the beginning of the map using begin()

  • Begin() and end() are member functions to help return the iterator object to the first element and the theoretical element following the last element.

  • Next, we have created a for each loop with a lambda expression to iterator from the start till the end of the map. To do this, we will need to include the <algorithm> header file.

  • This lambda expression acts as a callback to receive each map entry and finally prints it as the output.

Tip: To avoid writing std::string, std::cout, or std::map, or any other place where you have to use std you can write namespace std at the beginning of your code.

Check out the output for this code in the image below to see if all the elements are printed or not.

Output:

Traverse A Map Using std for each And Lambda Function Output

We see that ‘Joe’ having roll no 2 is printed as the last element. This is because the keys are stored in ascending or alphabetical order in the binary tree.

Reverse Iteration In C++ Maps

For containers like maps, we can traverse the map end to the beginning. This can be used when we need to process the data in reverse order. So, how do you traverse a map from the end in CPP? Let’s take a look at it with the coding example.

				
					#include <iostream>
#include <map>
#include <string>

using namespace std;
int main()
{

    // create a map named Student and insert the elements in it
    map<string, int> myMap = {{"Alex", 1}, {"Joe", 2}, {"Charlie",3}};
    
    // Reverse iterating using reverse iterators
    std::cout << "-------Reverse iteration of the map----------" << std::endl;
    for (auto it = myMap.rbegin(); it != myMap.rend(); ++it) {
        std::cout << it->first << " is having " << it->second << " Roll number." << std::endl;
    }
   
    return 0;
}
				
			

Explanation Of The Program:

  • In this case, we have a map myMap that has some data stored in the form of key and value pairs. The name key is for the string type and the value int is for the roll numbers.

  • For iterating in reverse order, we have to use the STL reverse iterators. These are – rbegin() iterator pointing to the last data value and rend() iterator pointing before the first data value.

  • By using the for loop, we will perform the traversing of the map in reverse or descending order.

The result for this program is given below. We will be able to see the names of the students in decreasing order.

Output:

Reverse Iteration In C++ Maps Output

Best Practices For Iteration Over Maps In C++

It is necessary to follow the best practices and conventions while writing any program in C++ or other programming languages. While working with maps, we should carefully consider healthy coding practices so that we are able to write clear and concise codes.

Here are some best practices that you can follow to build amazing and effective programs using maps.

  • Use Range-Based Loops – This is one of the most efficient techniques for map iterations. It simplifies the process and handles the iterator pointing to the elements on its own.

  • Use ‘const’ Keyword – We can use the const keyword to avoid unnecessary modifications in maps while we are traversing. This ensures that there are no runtime errors.

  • Avoid Unnecessary Copies by Using References – We can improve the performance of the code and handle a large map with complex data types or structured bindings by using references like auto& instead of simple auto.

Also, if you wish to know more aboutย C++ and its usesย then you can read our articleย to have a more clear understanding.

Conclusion

Using a map as a container in your program and iterating or traveling over it has different methods. Some of these are extremely simple like the grade school level, while others require careful implementation for them to function properly.

In this article, we saw how we can perform iteration on a map in C++ using methods like range-based loops and STL iterators. If you have any doubts related to the topic, feel free to reach out to us!

Takeaways:

  • There are multiple ways to traverse a map in C++. We can use loops, STL iterators, lambda functions, and reverse iterators as well.

  • If you want to store data using specific criteria, a map may be suitable for you. In computer science, the keys in this structure are stored in a balanced tree in increasing order.

  • Remember to use coding best practices while implementing maps so that your program is optimized and efficient.

Leave a Comment

Your email address will not be published. Required fields are marked *