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++
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > s;
s.insert(10);
s.insert(20);
s.insert(30);
for ( int x : s) {
cout << x << " " ;
}
return 0;
}
|
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++
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > v{ 10, 20, 30 };
set< int > s;
s.insert(v.begin(), v.end());
for ( int x : s) {
cout << x << " " ;
}
return 0;
}
|
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++
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > s;
s.insert({10, 20, 30, 20, 10});
for ( int x : s)
cout << x << " " ;
return 0;
}
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 Apr, 2023
Like Article
Save Article