How to Insert a Range of Elements in a Set in C++ STL?
Last Updated :
02 Dec, 2022
Prerequisites: Set in C++
Sets in C++ are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending.
Syntax:
set<datatype> set_name;
Some Basic Functions Associated with Set:
- begin(): Returns an iterator to the first element in the set.
- end(): Returns an iterator to the theoretical element that follows the last element in the set.
- size(): Returns the number of elements in the set.
- max_size(): Returns the maximum number of elements that the set can hold.
- empty(): Returns whether the set is empty.
Inserting an Iterator Range into a Set
It takes the range and inserts the element one by one into the BST if it is not already present in it in O(N log(N)) time.
Syntax:
set_name.insert(iterator Starting_position, iterator Ending_position);
Note: It insert element of Starting_position, Ending_position) which means Ending_position element is excluded.
Example:
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
set< int > s;
int arr[] = { 1, 2, 4, 3, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
s.clear();
s.insert(arr, arr + N);
cout << "Inserting an array of Size: " << N << endl;
cout << "Size of set: " << s.size() << endl;
for ( auto & i : s) {
cout << i << " " ;
}
return 0;
}
|
Output
Inserting an array of Size: 5
Size of set: 5
1 2 3 4 5
Example 2:
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
vector< int > v = { 1, 2, 4, 3, 5 };
set< int > s;
s.insert(v.begin(), v.end());
cout << "Inserting a vector of Size: " << v.size()
<< endl;
cout << "Size of set: " << s.size() << endl;
for ( auto & i : s) {
cout << i << " " ;
}
cout << endl;
return 0;
}
|
Output
Inserting a vector of Size: 5
Size of set: 5
1 2 3 4 5
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...