This post will discuss how to insert elements into a map in C++.

1. Using std::map::insert

The standard solution to insert new elements into a map is using the std::map::insert function. It inserts the specified key-value pair into the map only if the key already doesn’t exist. If the key already exists in the map, the element is not inserted.

Download  Run Code

Output:

{1, A}
{2, B}
{3, C}
{4, D}
{5, E}

 
This is functionally equivalent to the following code that uses std::make_pair to produce a std::pair<> via template deduction.

Download  Run Code

Output:

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

 
Or, even shorter, using the list initialization syntax:

Download  Run Code

Output:

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

2. Using operator[]

The std::map::insert function does not insert the specified key-value pair into the map if the key already exists. To overwrite the old value for an existing key, we can use operator[].

Download  Run Code

Output:

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

 
With C++17, std::map introduced the std::map::insert_or_assign insertion function. It is similar to operator[], but returns more information and does not require default-constructibility of the mapped type.

Download  Run Code

Output:

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

3. Using std::map::emplace

The std::map::emplace function inserts a new element into the map container if the key is not already present. It can be used as follows:

Download  Run Code

Output:

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

 
With C++17, std::map introduced the std::map::try_emplace function. It behaves like std::map::emplace, but does not move from rvalue arguments when no insertion happens (key already exist in the map). For example,

Download  Run Code

Output:

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

That’s all about inserting elements into a map in C++.