C++ Standard Library C++ STL Library

C++ map - emplace_hint() Function



The C++ map::emplace_hint function is used to insert a new element in the map with the hint of insertion position. The insertion of new element happens only when the key is not already present in the map. If insertion happens, it increases the size of the map by one. As a map is an ordered data container, hence it stores the new element in its respective position to keep the map 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

For successfully inserted element, returns an iterator pointed to newly added element. Otherwise, returns an iterator pointed to the equivalent element.

Time Complexity

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

Example:

In the example below, the map::emplace_hint function is used to insert new element in the map called MyMap.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<int, string> MyMap;
  map<int, string>::iterator it;
    
  MyMap[101] = "John";
  MyMap[102] = "Marry";
  MyMap[103] = "Kim";

  it = MyMap.begin();
  MyMap.emplace_hint(it, 104, "Jo");
  it = MyMap.emplace_hint(MyMap.end(), 105, "Ramesh");  

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

  return 0;
}

The output of the above code will be:

MyMap contains: 
 101  John
 102  Marry
 103  Kim
 104  Jo
 105  Ramesh

❮ C++ <map> Library