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++
// C++ program to insert elements into a set using iterator #include <iostream> #include <set> #include <vector> using namespace std; int main() { // initialzie a set set< int > s = { 10, 20, 30, 40, 50 }; // initialize a vector whose elements will be added into // the set vector< int > vec = { 60, 70, 80 }; // Printing the elements of the set before insertion cout << "Before Insertion:" ; for ( const auto & element : s) { cout << element << " " ; } cout << endl; // Inserting elements into the set using iterators s.insert(vec.begin(), vec.end()); // Printing the elements of the set after insertion cout << "After Insertion:" ; for ( const auto & element : s) { cout << element << " " ; } cout << endl; return 0; } |
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.
How to Insert Elements into a Set Using Iterator in C++?
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}
Contact Us