Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ multimap::emplace_hint function is used to insert a new element in the multimap with the hint of insertion position. The insertion of the new element increases the size of the multimap by one. As a multimap is an ordered data container, hence it stores the new element in its respective position to keep the multimap sorted.

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

Logarithmic i.e, Θ(log(n)).
Constant i.e, Θ(1) if the insertion point for the element is position.

Example:

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

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  multimap<string, string> MyMMap;
  multimap<string, string>::iterator it;

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

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

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

The output of the above code will be:

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

❮ C++ <map> Library