This post will discuss how to initialize a map in C++.

There are several approaches to initialize a std::map or std::unordered_map in C++, as shown below:

1. Using Initializer List

In C++11 and above, we can use the initializer lists '{...}' to initialize a map container.

Download  Run Code

Output:

{3 -> three}
{1 -> one}
{2 -> two}

 
Instead of using brackets, we can give something meaningful to construct pairs like specifying their fully qualified name or using std::make_pair.

Download  Run Code

Output:

{3 -> three}
{1 -> one}
{2 -> two}

 
We can also pass a binary predicate with std::map, which takes two values of the same type and defines the ordering of the map’s keys. The predicate returns true if the first parameter appears before the second parameter and false otherwise.

Download  Run Code

Output:

{3 -> three}
{2 -> two}
{1 -> one}

2. From array of pairs

We can use a range constructor to initialize the set from elements of an array of pairs or another container of pairs.

Download  Run Code

Output:

{3 -> three}
{1 -> one}
{2 -> two}

3. From another map

We can use a copy constructor to initialize a map from elements of another map.

Download  Run Code

Output:

{2 -> two}
{3 -> three}
{1 -> one}

4. Using Default Constructor

We can use the empty container constructor (or a default constructor) to construct an empty map (with no elements), as shown below:

Download  Run Code

Output:

The standard output is empty

That’s all about initializing a std::map or std::unordered_map in C++.