set emplace_hint() function in C++ STL

The set::emplace_hint() is a built-in function in C++ STL which inserts a new element in the set. A position is passed in the parameter of the function which acts as a hint from where the searching operation starts before inserting the element at its current position. The position only helps the process to get faster, it does not decide where the new element is to be inserted. The new element is inserted following the property of the set container only.

Syntax:

set_name.emplace_hint(iterator position, value) 

Parameters: The function accepts two mandatory parameters which are described below:

  • position: This parameter acts as a hint from where the searching operation is done before inserting the element at its current position. The position only helps the process to be faster, it does not decide where the new element is to be inserted. The new element is inserted following the property of the set container only.
  • value: This specifies the element to inserted in the set container. The value is inserted into the set if it is not present before.

Return Value: The function returns an iterator pointing to the position where the insertion is done. If the element passed in the parameter already exists, then it returns an iterator pointing to the position where the existing element is.

Below program illustrates the above function.

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to demonstrate the
// set::emplace_hint() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
  
    set<int> s;
    auto it = s.emplace_hint(s.begin(), 1);
  
    // stores the position of 2's insertion
    it = s.emplace_hint(it, 2);
  
    // fast step as it directly
    // starts the search step from
    // position where 3 was last inserted
    s.emplace_hint(it, 3);
  
    // this is a slower step as
    // it starts checking from the
    // position where 3 was inserted
    // but 0 is to be inserted before 1
    s.emplace_hint(it, 0);
  
    // prints the set elements
    for (auto it = s.begin(); it != s.end(); it++)
        cout << *it << " ";
  
    return 0;
}

chevron_right


Output:

0 1 2 3


My Personal Notes arrow_drop_up

The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.