Open In App

How to Merge Multiple std::sets into a Single std::set in C++?

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++ programt to show the merging of multiple sets into a
// single set using merge algorithm.
  
#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
  
// driver code
int main()
{
  
    // creating multiple sets
    set<int> set1 = { 1, 2, 1, 3 };
    set<int> set2 = { 3, 4, 5, 4 };
  
    // merging the set by calling the function
    set<int> finalSet;
    merge(set1.begin(), set1.end(), set2.begin(),
          set2.end(), inserter(finalSet, finalSet.begin()));
    // printing the merged set
    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)

Article Tags :