How to Insert Elements into a Set Using Iterator in C++?
Last Updated :
09 Feb, 2024
In C++, a set is a container provided by the Standard Template Library(STL) that stores unique elements of the same type in a sorted order. In this article, we will learn how to use an iterator to insert elements into a set in C++.
Example:
Input:
myVector = {10, 20, 30, 40, 50}
Output:
myVector = {10, 20, 30, 40, 50, 60, 70, 80}
Insert Elements into a Set Using Iterator in C++
In C++, the std::set contains the std::set::insert() member function that also accepts iterators denoting a range of elements to be inserted in the set. These iterators can belong to any data container such as vector, deque, and even another set.
C++ Program to Insert Elements into a Set Using Iterator
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
set< int > s = { 10, 20, 30, 40, 50 };
vector< int > vec = { 60, 70, 80 };
cout << "Before Insertion:" ;
for ( const auto & element : s) {
cout << element << " " ;
}
cout << endl;
s.insert(vec.begin(), vec.end());
cout << "After Insertion:" ;
for ( const auto & element : s) {
cout << element << " " ;
}
cout << endl;
return 0;
}
|
Output
Before Insertion:10 20 30 40 50
After Insertion:10 20 30 40 50 60 70 80
Time Complexity: O(M logN) where N is the number of elements in the set and M is the number of elements in the vector.
Auxilary Space: O(M)
Note: If you are looking for a method to insert element at a particular position in a set using iterator, it is not possible as set always store data in some order.
Share your thoughts in the comments
Please Login to comment...