std::unordered_set provides the different overloaded versions of insert() member function to insert elements i.e.

Let’s see each of them in detail

Inserting element in unordered_set by value

For this we will use basic version of insert() member function i.e.

Insert() function will try to insert passed argument into the unordered_set and it returns a pair of an iterator and bool flag i.e.

What does this pair contain?

If an element equivalent to passed element is not present in the set, then new element will be inserted successfully and it will return the pair with following values,

  • Iterator will point to newly inserted element
  • Bool flag will be true.

If an element equivalent to passed element is already present in set, then new element will be not be inserted in set and it will return the pair with following values,

  • Iterator will point to the position of first matched equivalent element
  • Bool flag will be false.

Example,

Declare an unordered_set and insert few values i.e.

No try to insert a duplicate element and use the returned value to check id insertion is successful or not i.e.

As element with value 6 was already present therefore it was not inserted again.

Insert elements in unordered_set from an another container or array

std::unordered_set provides an another overloaded version of insert() that accepts a range i.e.

Using this we can insert elements from any container or array into the unordered_set. Let’s see how to insert elements from a vector into the unordered_set i.e.

This will insert all the elements from vector to the unordered_set. But, as unordered_set can contain the unique elements only.

 

Therefore, only following elements will be stored in set i.e.

3,4,1,2,9,5,6

Insert elements in unordered_set from an initializer_list

Complete working example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.