unordered_set emplace() function in C++ STL

The unordered_set::emplace() function is a built-in function in C++ STL which is used to insert an element in an unordered_set container. The element is inserted only if it is not already present in the container. This insertion also effectively increases the container size 1.

Syntax:

unordered_set_name.emplace(element)

Parameter: This function accepts a single parameter element which is to be inserted in the unordered_set container.



Return Value: This function returns a pair on successful insertion. The pair consists of an iterator pointing to the newly inserted element and a boolean value True. If the element to be inserted is already present in the container then it returns a pair with an iterator pointing to the already present element and a boolean value false.

Below programs illustrate the unordered_set::emplace() function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// unordered_set::emplace() function
  
#include <iostream>
#include <unordered_set>
  
using namespace std;
  
int main()
{
  
    unordered_set<int> sampleSet;
  
    // Inserting elements
    sampleSet.emplace(5);
    sampleSet.emplace(10);
    sampleSet.emplace(15);
    sampleSet.emplace(20);
    sampleSet.emplace(25);
  
    // displaying all elements of sampleSet
    cout << "sampleSet contains: ";
    for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) {
        cout << *itr << " ";
    }
  
    return 0;
}

chevron_right


Output:

sampleSet contains: 25 5 10 15 20

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// unordered_set::emplate() function
  
#include <iostream>
#include <unordered_set>
  
using namespace std;
  
int main()
{
  
    unordered_set<string> sampleSet;
  
    // Inserting elements using
    // emplace() function
    sampleSet.emplace("Welcome");
    sampleSet.emplace("To");
    sampleSet.emplace("GeeksforGeeks");
    sampleSet.emplace("Computer Science Portal");
    sampleSet.emplace("For Geeks");
  
    // displaying all elements of sampleSet
    cout << "sampleSet contains: ";
    for (auto itr = sampleSet.begin(); itr != sampleSet.end(); itr++) {
        cout << *itr << " ";
    }
  
    return 0;
}

chevron_right


Output:

sampleSet contains: Welcome To GeeksforGeeks For Geeks Computer Science Portal


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.