This post will discuss how to copy entries of a map to another map in C++.

1. Using std::map::insert

The standard approach to copy elements from a map to an “existing” map in C++ is using the std::map::insert member function. For example, the following code will insert all the elements from the beginning to the end of the first map into the second map.

This assumes that the map does not contain any common keys. In case a key already exists in the map, the new value will be discarded, and the old value will be retained.

Download  Run Code

Output:

{four, 4}
{one, 1}
{three, 3}
{two, 2}

2. Using Map Constructor

Another good option is to use the copy constructor to construct a map with a copy of each of the elements in the specified map. This is the preferred way to clone a map, as shown below:

Download  Run Code

Output:

{one, 1}
{three, 3}
{two, 2}

 
This is equivalent to the following code using the assignment operator:

Download  Run Code

Output:

{one, 1}
{three, 3}
{two, 2}

 
Since C++17, we can omit the map’s template arguments and let the compiler deduce them:

Download  Run Code

Output:

{one, 1}
{three, 3}
{two, 2}

3. Using std::map::merge

Starting with C++17, we can use the std::map::merge member function to copy content from a map to another map. This is the recommended way to copy the contents of a map to an existing map in C++17 and above.

Download Code

Output:

{four, 4}
{one, 1}
{three, 3}
{two, 2}

That’s all about copying entries of a map to another map in C++.