Set emplace_hint() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we are going to discuss the set::emplace_hint() function in C++ STL, their syntax, working and their return values.

What is Set in C++ STL?

Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees.

What is set::emplace_hint()

emplace_hint() function is an inbuilt function in C++ STL, which is defined in header file. This function inserts a new element in the set container with a position. In emplace_hint() we pass the element with a position, the position acts as a hint. The element is inserted if and only if there is no other value equal to the value which is to be inserted. The function searches from the hint position and finds the position where the element is to be emplaced.

Syntax

Set1.emplace_hint(iterator position, const type_t& value);

Parameter

This function accepts two parameters, one for the hint position and second is the element which is to be emplaced.

Position − This is hint position, from where the searching starts to find the position of the value to be emplaced. This position just happen to make the working of the function faster, this function doesn’t specify the exact location of the element which is to be emplaced.

Value − The real value which we have to emplace.

Return value

This function returns the iterator to the newly inserted element if the element is successfully inserted.

Example

Input: set mySet;
mySet.emplace_hint(mySet.begin(), 0);
mySet.emplace_hint(i, 1);
mySet.emplace_hint(i, 2);
mySet.emplace_hint(i, 1);
Output: Elements are : 0 1 2

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   set<int> mySet;
   auto i = mySet.emplace_hint(mySet.begin(), 0);
   i = mySet.emplace_hint(i, 1);
   mySet.emplace_hint(i, 2);
   mySet.emplace_hint(i, 1);
   cout<<"elements are : ";
   for (auto i = mySet.begin(); i != mySet.end(); i++)
      cout << *i<< " ";
   return 0;
}

Output

If we run the above code then it will generate the following output −

Elements are : 0 1 2

Example

 Live Demo

#include <iostream>
#include <set>
#include <string>
int main (){
   std::set<std::string> mySet;
   auto i = mySet.cbegin();
   mySet.emplace_hint (i,"best");
   i = mySet.emplace_hint (mySet.cend(),"point");
   i = mySet.emplace_hint (i,"is the");
   i = mySet.emplace_hint (i,"tutorials");
   std::cout<<"string is : ";
   for(const std::string& str: mySet)
      std::cout << ' ' << str;
   std::cout << '\n';
   return 0;
}

Output

If we run the above code then it will generate the following output −

String is : best is the point tutorials
raja
Published on 05-Mar-2020 14:30:08
Advertisements