Different Ways to Insert Elements in Set in C++ STL
Prerequisites:
The C++ Standard Template Library offers containers called Sets. It functions essentially in the same ways as a binary search tree and is used to store different elements in increasing/decreasing order.
There are different methods to insert elements in the set as mentioned below:
- Adding one element to set
- Inserting an Iterator Range into a Set
- Inserting an Initializer List in the Set
1. Adding one element to set
The basic way to add an element is a set is to use an insert() function where the value of the element is passed as a parameter to this function.
Syntax:
set_name.insert(element)
// C++ program for inserting
// Elements In set
// one by one
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Create an empty set
set<int> s;
// Adding values to the set
s.insert(10);
s.insert(20);
s.insert(30);
// Printing the set
for (int x : s) {
cout << x << " ";
}
return 0;
}
Output
10 20 30
Time Complexity : O(log n)
Auxiliary Space : O(n)
2. Inserting an Iterator Range into a Set
We can insert any other container elements into sets using iterators. In order to insert a range of elements from another container 2 parameters are required which are basically iterators pointing to starting and ending elements of that range.
Syntax:
set_name.insert(Iterator starting, Iterator ending);
// C++ program to Insert
// Elements In set using
// Iterator Range
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v{ 10, 20, 30 };
// Create an empty set
set<int> s;
// Inserting values of vector to set
s.insert(v.begin(), v.end());
// Printing the set
for (int x : s) {
cout << x << " ";
}
return 0;
}
Output
10 20 30
3. Inserting an Initializer List in Set
One more way to add the elements to a set is by inserting all elements from a list into the set. Given below is the syntax for this approach.
Syntax:
set_name.insert({element1,element2,element3,element4});
// C++ program for inserting
// Elements in set using
// Initializer List
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Create an empty set
set<int> s;
// Inserting all elements of the list
// As we are inserting into set so the
// duplicate elements are rejected
// and only one occurrence is considered.
s.insert({10, 20, 30, 20, 10});
// Printing the set
for (int x : s)
cout << x << " ";
return 0;
}
Output
10 20 30