C++ Standard Library C++ STL Library

C++ unordered_multimap - emplace_hint() Function



The C++ unordered_multimap::emplace_hint function is used to insert a new element in the unordered_multimap with the hint of insertion position. The insertion of the new element increases the size of the unordered_multimap 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

Returns an iterator pointed to newly added element.

Time Complexity

Average case: Constant i.e, Θ(1).
Worst case: Linear i.e, Θ(n).

Example:

In the example below, the unordered_multimap::emplace_hint function is used to insert a new element in the unordered_multimap called uMMap.

#include <iostream>
#include <unordered_map>
using namespace std;
 
int main (){
  unordered_multimap<string, string> uMMap;
  unordered_multimap<string, string>::iterator it;

  uMMap.insert(pair<string, string>("USA", "New York"));
  uMMap.insert(pair<string, string>("USA", "Washington"));  
  uMMap.insert(pair<string, string>("CAN", "Toronto"));

  it = uMMap.begin();
  uMMap.emplace_hint(it, "CAN", "Montreal");
  it = uMMap.emplace_hint(uMMap.end(), "IND", "Delhi"); 

  cout<<"uMMap contains: \n ";
  for(it = uMMap.begin(); it != uMMap.end(); ++it)
     cout<<it->first<<"  "<<it->second<<"\n ";

  return 0;
}

The output of the above code will be:

uMMap contains: 
 IND  Delhi
 CAN  Toronto
 CAN  Montreal
 USA  Washington
 USA  New York

❮ C++ <unordered_map> Library