C++ unordered_map - emplace_hint() Function
The C++ unordered_map::emplace_hint function is used to insert a new element in the unordered_map with the hint of insertion position. 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.
The hint is only used to speed up the insertion process considering the actual insertion point is either specified position or close to it.
Syntax
template <class... Args> iterator emplace_hint (const_iterator position, Args&&... args);
Parameters
position |
Specify hint for the position where the element can be inserted. |
args |
Arguments forwarded to construct the new element of the mapped type. |
Return Value
For successfully inserted element, returns an iterator pointed to newly added element. Otherwise, returns an iterator pointed to the equivalent element.
Time Complexity
Average case: Constant i.e, Θ(1).
Worst case: Linear i.e, Θ(n).
Example:
In the example below, the unordered_map::emplace_hint 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; unordered_map<int, string>::iterator it; uMap[101] = "John"; uMap[102] = "Marry"; uMap[103] = "Kim"; it = uMap.begin(); uMap.emplace_hint(it, 104, "Jo"); it = uMap.emplace_hint(uMap.end(), 105, "Ramesh"); cout<<"uMap contains: \n "; for(it = uMap.begin(); it != uMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n "; return 0; }
The output of the above code will be:
uMap contains: 105 Ramesh 104 Jo 103 Kim 102 Marry 101 John
❮ C++ <unordered_map> Library