C++ Standard Library C++ STL Library

C++ unordered_set - emplace() Function



The C++ unordered_set::emplace function is used to insert a new unique element in the unordered_set. The insertion of new element happens only when it is not already present in the unordered_set. If insertion happens, it increases the size of the unordered_set by one.

Syntax

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

Parameters

args Arguments forwarded to construct the new element.

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

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

Example:

In the example below, the unordered_set::emplace function is used to insert new element in the unordered_set called uSet.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_set<int> uSet{10, 20, 30, 40, 50};
  
  //insert a new unique element in the unordered_set
  auto NewInsert = uSet.emplace(60);
  
  if(!NewInsert.second) 
     cout<<"60 is already present in uSet.\n";
  else
     cout<<"60 is added in uSet.\n";

  //insert an already present element in the unordered_set
  NewInsert = uSet.emplace(10);

  if(!NewInsert.second) 
     cout<<"10 is already present in uSet.\n";
  else
     cout<<"10 is added in uSet.\n";

  return 0;
}

The output of the above code will be:

60 is added in uSet.
10 is already present in uSet.

❮ C++ <unordered_set> Library