unordered_set emplace_hint() function in C++ STL

The unordered_set::emplace_hint() function is an inbuilt function in C++ STL which inserts a new element in the unordered_set only if the value to be inserted is unique, with a given hint.

Syntax:

unordered_set_name.emplace_hint( position, value )

Parameter: This function accepts two parameters as mentioned above and described below:

  • position: This parameter is used to describe the position for inserted operation.
  • value: This parameter is used to hold the which needs to insert.

Return Value: If the value is not present in the unordered_set, then the function inserts the value and returns an iterator pointing to the inserted element. Else, if the value is already present in the unordered_set, then the function returns the iterator pointing to that element.

Below program illustrates the unordered_set::emplace_hint() function in C++ STL:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate
// unordered_set::emplace_hint() function
#include <iostream>
#include <unordered_set>
using namespace std;
  
// main program
int main()
{
  
    // Initialize an unordered_set
    unordered_set<int> uset = { 20, 40, 50, 60 };
  
    // Insert an element that is not present
    uset.emplace_hint(uset.begin(), 80);
  
    // Display uset
    cout << "uset: ";
    for (auto it = uset.begin(); it != uset.end(); it++)
        cout << *it << " ";
}

chevron_right


Output:

uset: 80 20 40 50 60

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate
// unordered_set::emplace_hint() function
#include <iostream>
#include <unordered_set>
using namespace std;
  
// main program
int main()
{
  
    // Initialize an unordered_set
    unordered_set<int> uset = { 20, 40, 50, 60 };
  
    // Try to Insert an element that is not present
    uset.emplace_hint(uset.begin(), 50);
  
    // Display uset
    cout << "uset: ";
    for (auto it = uset.begin(); it != uset.end(); it++)
        cout << *it << " ";
}

chevron_right


Output:

uset: 60 50 40 20


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.