In this article we will discuss the different ways to insert elements in an unordered_map.

Unordered_map provides different overloaded versions of insert() member function to insert key value pairs in an unordered_map. Lets discuss them one by one.

Inserting multiple elements in unordered_map through an initializer_list

unordered_map provides an overloaded version of insert that accepts an initializer_list i.e.

It inserts the multiple key value pair in the map i.e.

With the we can insert multiple elements in map. But, as map contains can contain only unique keys, so what if we add elements with duplicate key. This version of insert() function returns void , so there is no way to know which elements are added and which are not. Therefore, for such scenarios we need different overloaded version of insert() i.e.

Inserting a single element in an unordered_map and check result

unordered_map provides an overloaded version of insert that accepts an std::pair of key – value and inserts the element in map i.e.

It returns a pair of Iterator and bool.  bool variable in pair will be true if element is inserted successfully else it will be false. If element is inserted successfully then iterator in pair will point to the newly inserted element in map.

Let’s see an example,

Also, instead of creating pair and then inserting, we can also insert the value_type using same version of insert i.e.

Complete working example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.