C++ Standard Library C++ STL Library

C++ unordered_multimap - emplace() Function



The C++ unordered_multimap::emplace function is used to insert a new element in the unordered_multimap. The insertion of the new element increases the size of the unordered_multimap by one.

Syntax

template <class... Args>
iterator emplace (Args&&... args);

Parameters

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 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"));

  //insert a new element in the uMMap using emplace function
  uMMap.emplace("IND", "Delhi");
  uMMap.emplace("CAN", "Montreal");
  
  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 => Montreal
 CAN => Toronto
 USA => Washington
 USA => New York

❮ C++ <unordered_map> Library