How to iterate over an unordered_map in C++11

In this article we will discuss the different ways to iterate over an unordered_map.


First lets create an unordered_map and then we will see the different ways to iterate over it.

// Initialize an unordered_map through initializer_list
std::unordered_map<std::string, int> wordMap({{ "First", 1 },{ "Second", 2 },{ "Third", 3 }});

Iterating an unordered_map using range based for loop

// Iterate over an unordered_map using range based for loop
for (std::pair<std::string, int> element : wordMap)
{
	std::cout << element.first << " :: " << element.second << std::endl;
}

Iterating an unordered_map using Iterators

// Get an iterator pointing to begining of map
std::unordered_map<std::string, int>::iterator it = wordMap.begin();

// Iterate over the map using iterator
while(it != wordMap.end())
{
	std::cout<<it->first << " :: "<<it->second<<std::endl;
	it++;
}

Iterating an unordered_map using std::for_each and Lambda Functions

std::for_each(wordMap.begin(), wordMap.end() , [](std::pair<std::string, int > element){
				std::cout<<element.first << " :: "<<element.second<<std::endl;
				});

Complete Working Example is as follows,

#include <iostream>
#include <unordered_map>
#include <string>
#include <algorithm>

int main()
{
// Initialize an unordered_map through initializer_list
	std::unordered_map<std::string, int> wordMap(
	{
	{ "First", 1 },
	{ "Second", 2 },
	{ "Third", 3 } });

// Iterate over an unordered_map using range based for loop
	for (std::pair<std::string, int> element : wordMap)
	{
		std::cout << element.first << " :: " << element.second << std::endl;
	}

	std::cout << "*******************" << std::endl;

// Get an iterator pointing to begining of map
	std::unordered_map<std::string, int>::iterator it = wordMap.begin();

// Iterate over the map using iterator
	while (it != wordMap.end())
	{
		std::cout << it->first << " :: " << it->second << std::endl;
		it++;
	}

	std::cout << "*******************" << std::endl;

	std::for_each(wordMap.begin(), wordMap.end(),
			[](std::pair<std::string, int > element)
			{
				std::cout<<element.first << " :: "<<element.second<<std::endl;
			});

	return 0;
}

Output:

Third :: 3
First :: 1
Second :: 2
*******************
Third :: 3
First :: 1
Second :: 2
*******************
Third :: 3
First :: 1
Second :: 2

 

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top