C++ set insert()

C++ set insert() is used for inserting new element in the set.

Because element keys are unique in a set, the insertion operation first checks that whether the given key is already present in the set or not, if the key is present in the set then it is not inserted in the set and the iterator to the existing key is returned otherwise new element is inserted in the set.

Syntax

Parameter

val: value to insert in the set.

position: Hint for the position to insert element in the set.

first: Beginning of range to insert.

last: End of range to insert.

il: An initializer list.

Return value

Returns a bool pair to indicate whether insertion is happened or not and returns an iterator pointing to the newly inserted element.

Complexity

  • If a single element is inserted complexity will be logarithmic in size.
  • If a hint is given and the position given is the optimal then the complexity will be amortized constant.

Iterator validity

No changes.

Data Races

The container is modified.

Exception Safety

This function does not throw exception.

Example 1

Let's see the simple example to insert the elements into the set:

Output:

The elements in set are: 1 2 3 4 5

In the above example, it simply inserts the element with the given key.

Example 2

Let's see a simple example to insert the element in the specified position:

Output:

The elements in set are: 1 2 3 4 5  

In the above example, elements are inserted in the defined position.

Example 3

Let's see a simple example to insert the elements of one set to another in a given range:

Output:

The elements in set1 are: 1 2 3 4 5 
The elements in set2 are: 3 4 5  

Example 4

Let's see a simple example to insert the elements from the initializer list:

Output:

Set contains following elements
C++
Java
Oracle
SQL
VB

In the above example, elements are inserted from an initializer list.






Latest Courses