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.
- map emplace() in C++ STL
- set::emplace() in C++ STL
- stack emplace() in C++ STL
- multimap::emplace() in C++ STL
- deque emplace in C++ STL
- multiset::emplace() in C++ STL
- priority_queue emplace() in C++ STL
- queue::emplace() in C++ STL
- emplace vs insert in C++ STL
- unordered_multimap emplace() function in C++ STL
- list emplace() function in C++ STL
- unordered_set emplace() function in C++ STL
- unordered_multiset emplace() function in C++ STL
- vector emplace() function in C++ STL
- Inserting elements in std::map (insert, emplace and operator )
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.