C++ Standard Library C++ STL Library

C++ unordered_set - emplace_hint() Function



The C++ unordered_set::emplace_hint function is used to insert a new unique element in the unordered_set with the hint of insertion position. 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.

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.

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

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

Example:

In the example below, the unordered_set::emplace_hint 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}; 
  unordered_set<int>::iterator it;

  it = uSet.begin();
  uSet.emplace_hint(it, 60);
  it = uSet.emplace_hint(uSet.end(), 70);

  cout<<"uSet contains: ";
  for(it = uSet.begin(); it != uSet.end(); ++it)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

uSet contains: 70 60 10 20 30 40 50 

❮ C++ <unordered_set> Library

5