C++ Standard Library C++ STL Library

C++ map - emplace() Function



The C++ map::emplace function is used to insert a new element in the map if the key is unique. 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.

Syntax

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

Parameters

args Arguments forwarded to construct the new element of the mapped type.

Return Value

For successfully inserted element, returns a pair of an iterator pointed to newly added element and a value of true. Otherwise, returns a pair of an iterator pointed to equivalent element and a value of false.

Time Complexity

Logarithmic i.e, Θ(log(n)).

Example:

In the example below, the map::emplace 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;
  
  MyMap[101] = "John";
  MyMap[102] = "Marry";
  MyMap[103] = "Kim";

  //insert a new element with unique key in the MyMap
  auto NewInsert = MyMap.emplace(104, "Jo");
  
  if(!NewInsert.second) 
     cout<<"104 key is already present in MyMap.\n";
  else
     cout<<"[104, Jo] is added to MyMap.\n";

  //insert a new element with already present key in the MyMap
  NewInsert = MyMap.emplace(102, "Ramesh");

  if(!NewInsert.second) 
     cout<<"102 key is already present in MyMap.\n";
  else
     cout<<"[102, Ramesh] is added to MyMap.\n";

  return 0;
}

The output of the above code will be:

[104, Jo] is added to MyMap.
102 key is already present in MyMap.

❮ C++ <map> Library