C++ Standard Library C++ STL Library

C++ set - emplace_hint() Function



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

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 set::emplace_hint function is used to insert new element in the set called MySet.

#include <iostream>
#include <set>
using namespace std;
 
int main (){
  set<int> MySet{10, 20, 30, 40, 50};
  set<int>::iterator it;

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

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

  return 0;
}

The output of the above code will be:

MySet contains: 10 20 30 40 50 60 70 

❮ C++ <set> Library