How to Merge Multiple std::sets into a Single std::set in C++?
Last Updated :
29 Jan, 2024
In C++, merging multiple sets into a single set means we just need to combine all the unique elements of different given sets into one single set. In this article, we will discuss how to merge multiple sets into a single set.
For Example,
Input:
set1 = {1, 2};
set2 = {2, 4, 5};
set3 = {1, 4, 5, 6, 7, 8};
Output:
final_set = {1, 2, 4, 5, 6, 7, 8};
Merging Multiple Sets in C++
We can use the std::merge algorithm to merge two sets in C++. To merge multiple sets, we can call the merge algorithm multiple times. std::merge is defined inside <algorithm> header so we need to include it before compilation.
C++ Program to Merge Multiple Sets
C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main()
{
set< int > set1 = { 1, 2, 1, 3 };
set< int > set2 = { 3, 4, 5, 4 };
set< int > finalSet;
merge(set1.begin(), set1.end(), set2.begin(),
set2.end(), inserter(finalSet, finalSet.begin()));
cout << "Merged set: " << endl;
for ( int it : finalSet) {
cout << it << " " ;
}
return 0;
}
|
Output
Merged set:
1 2 3 4 5
Time Complexity: O(N log N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...