In this article we will discuss different ways to insert an element in Set.

Set provides 3 different overloaded version of insert() function to add element in set. Let’s discuss them one by one,

Inserting a Single element in Set and checking the result

Set is an associative container and contains only unique elements, therefore an insertion in set can fail if
a similar element is already present in set. Keeping that in mind set provides a version of member function
insert() i.e.

It accepts the element to be inserted and returns a pair of Iterator & bool flag.

If insertion is successful then value of bool flag in returned pair will be true and iterator in it will
point to the newly inserted element.
Whereas, if insertion is failed because it was a duplicate element then bool flag in returned pair will be false.

Suppose we have a set of strings i.e.

Inserting an element with insert() i.e.

Check out complete example as follows,

Output:

 

Inserting an Iterator Range into a Set

std::set provides an another overloaded version of insert() i.e.

It accepts a range of input iterators and one by one all the elements in set while traversing through the range( first to last-1).

Check out the example, we are inserting elements from a vector to set by giving its iterator range to insert() function i.e.

Output:

It will only add unique elements in set and reject the duplicate ones. As this version of overloaded insert() function doesn’t return any value. Hence, we have no information after the call, that what elements were actually inserted and what got rejected.

Similarly, we can insert elements from other containers too by providing a range of iterators to the insert() function.

Inserting a Initializer List in Set

std::set provides an another overloaded version of insert() i.e.

It accepts a initializer list and insert all elements in it to the set.

Check out the example, we are inserting elements from an initiazer list to the set i.e.

Output:

It will only add unique elements in set and reject the duplicate ones. As this version of overloaded insert() function doesn’t return any value.
Hence, we have no information after the call, that what elements were actually inserted and what got rejected.

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