C++ unordered_map - emplace() Function
The C++ unordered_map::emplace function is used to insert a new unique element in the unordered_map. The insertion of new element happens only when the key is not already present in the unordered_map. If insertion happens, it increases the size of the unordered_map by one.
Syntax
template <class... Args> pair<iterator,bool> emplace (Args&&... args);
Parameters
args |
Arguments forwarded to construct the new element of the mapped type. |
Return Value
For successfully inserted element, returns a pair of an iterator pointed to newly added element and a value of true. Otherwise, returns a pair of an iterator pointed to equivalent element and a value of false.
Time Complexity
Average case: Constant i.e, Θ(1).
Worst case: Linear i.e, Θ(n).
Example:
In the example below, the unordered_map::emplace function is used to insert new element in the unordered_map called uMap.
#include <iostream> #include <unordered_map> using namespace std; int main (){ unordered_map<int, string> uMap; uMap[101] = "John"; uMap[102] = "Marry"; uMap[103] = "Kim"; //insert a new element with unique key in the uMap auto NewInsert = uMap.emplace(104, "Jo"); if(!NewInsert.second) cout<<"104 key is already present in uMap.\n"; else cout<<"[104, Jo] is added in uMap.\n"; //insert a new element with already present key in the uMap NewInsert = uMap.emplace(102, "Ramesh"); if(!NewInsert.second) cout<<"102 key is already present in uMap.\n"; else cout<<"[102, Ramesh] is added in uMap.\n"; return 0; }
The output of the above code will be:
[104, Jo] is added in uMap. 102 key is already present in uMap.
❮ C++ <unordered_map> Library