The unordered_set::insert() is a built-in function in C++ STL which is used to insert a new {element} in the unordered_set container. Each element is inserted only if it is not equivalent to any other elements already present in the container (elements in an unordered_set have unique values). The insertion is done automatically at the position according to the container’s criterion. This effectively increases the container size by the number of elements inserted.
Syntax:
unordered_set_name.insert (Value) or, unordered_set_name.insert (InputIterator first, InputIterator last)
Parameters:
- Value: It specifies the value which is to be inserted in the container.
- first, last: Iterators specifying a range of elements. Copies of the elements in the range [first, last) are inserted in the unordered_set container. Keep in mind that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
Return Value: The function returns an iterator pointing either to the newly inserted element in the container or to the element whose key is equivalent.
Below programs illustrate the above function:
Program 1:
#include<iostream>#include <string>#include <unordered_set>using namespace std; int main(){ unordered_set<string> mySet = { "first", "third" }; string myString = "tenth"; // inserts key in set mySet.insert(myString); cout << "My set contains:" << endl; for (const string& x : mySet) { cout << x << " "; } cout << endl; return 0;} |
My set contains: tenth first third
Program 2:
// C++ program to illustrate// unordered_set::insert() #include <array>#include <iostream>#include <string>#include <unordered_set>using namespace std; int main(){ unordered_set<std::string> mySet = { "first", "third", "second" }; array<std::string, 2> myArray = { "tenth", "seventh" }; string myString = "ninth"; mySet.insert(myString); // array elements range insertion in set mySet.insert(myArray.begin(), myArray.end()); // initializer list insertion mySet.insert({ "fourth", "sixth" }); cout << "myset contains:" << endl; for (const string& x : mySet) { cout << x << " "; } cout << endl; return 0;} |
myset contains: sixth fourth seventh first tenth second third ninth


