unordered_map emplace() in C++ STL
The unordered_map::emplace() is a built-in function in C++ STL which inserts the key and its element in the unordered_map container. It effectively increases the container size by one. If the same key is emplaced more than once, the map stores the first element only as the map is a container which does not store multiple keys of the same value.
How is it different from unordered_map insert()?
The advantage of emplace is, it does in-place insertion and avoids an unnecessary copy of object. For primitive data types, it does not matter which one we use. Please refer this for details.
Parameters: The function accepts two mandatory parameters which are described below:
- key – specifies the key to be inserted in the multimap container.
- element – specifies the element to the key which is to be inserted in the map container.
Return values: It returns a pair of an iterator and a bool. If the element already exists, it returns an iterator pointing to the already inserted element and if the element does not exist it returns an iterator to newly added container. The bool represents whether the insertion took place or not.
Below program illustrate the working of emplace function:
4==>>50 2==>>30 1==>>40
Example 2: Let’s say that we want to display all unique characters with there indices for a string. If a character appears multiple times then display the index at which it appeared first.
r==>>7 e==>>1 s==>>4 g==>>0 k==>>3 f==>>5 o==>>6
Explanation: “g” appeared 2 times in the string 1st at index “0” and then at index “8” but emplace function does not let us save in unordered_map until the given key is unique. That is why “0” is saved and “8” didn’t.
Similarly for “e”, “1” is saved and “2”, “9”, “10” didn’t.