This post will discuss how to print out all keys and values from a std::map or std::unordered_map in C++.

Maps are associative containers whose elements are key-value pairs. Using a map, we can associate a value with some key and later retrieve that value using the same key. The retrieval operation in a map is very fast. There are several ways in C++ to print out all pairs present on the map:

1. Using range-based for-loop

The recommended approach in C++11 is to use the new range-based for-loops for printing the map pairs, as shown below:

Download  Run Code

Output:

{3: C}
{1: A}
{2: B}

2. Using std::for_each function

Another simple solution is to use std::for_each. It takes an iterator to the beginning and end of the map, and applies a specified function on every pair within that range. The specified function may be a unary function, a lambda expression, or an object of a class overloading the () operator.

Download  Run Code

Output:

{3: C}
{1: A}
{2: B}

3. Using Iterator

We can also use iterators to iterate a map and print its pairs. It is recommended to use the const_iterator from C++11, as we’re not modifying the map pairs inside the for-loop.

Download  Run Code

Output:

{3: C}
{1: A}
{2: B}

4. Operator<< Overloading

To get std::cout to accept the map object, we can overload the << operator to recognize an ostream object on the left and a map object on the right, as shown below:

Download  Run Code

Output:

{3: C}
{1: A}
{2: B}

That’s all about printing out all keys and values from a map in C++.