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

1. Using copy constructor

We can use a copy constructor to initialize a map from elements of another map. We can also use operator= to copy a map, that is functionally the same as above. This is demonstrated below:

Download  Run Code

Output:

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

2. Using std::map::insert

Another option is to use the std::map::insert function that extends the map container by inserting the elements from the specified range, as shown below. This function can be used if the map already contains some key-value pairs.

Download  Run Code

Output:

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

3. Using std::copy

Finally, we can use the std::copy standard algorithm with an insert iterator to copy the contents of the original map to another map. The following solution demonstrates this using std::inserter, defined in header <iterator>:

Download  Run Code

Output:

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

That’s all about copying a map in C++.