Open In App

How to Find the Union of Two Sets in C++?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, sets are STL containers that store unique elements of the same type in a sorted manner. No duplicate elements are allowed in the sets, as the value of every element in a set is unique. In this article, we will learn how to find the union of two sets in C++.

Example

Input:
set1 = {12 , 13, 14 , 15 , 16}
set2= {13, 14 , 18 , 19 , 20}

Output:
union = { 12 , 13 , 14 , 15 , 16 , 18 , 19 , 20 }

Finding the Union of Two Sets in C++

In C++, you can find the union of two std::set using the std::set_union() function. This function takes the iterator to the beginning and the end of the two sets and also to the beginning of the data container where we want to store the union.

Syntax

set_union(set1.begin(), set1.end(), set2.begin() , set2.end(), unionset.begin())

C++ Program to Find the Union of Two Sets

C++




// C++ program to Find the Union of Two Sets
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
  
// Driver Code
int main()
{
  
    // given two set
    set<int> set1 = { 11, 12, 13, 14, 15 };
    set<int> set2 = { 14, 15, 16, 17, 18 };
  
    // Create a vector to store the union
    vector<int> unionSet(set1.size() + set2.size());
  
    // Find the union using set_union method
    auto it
        = set_union(set1.begin(), set1.end(), set2.begin(),
                    set2.end(), unionSet.begin());
  
    // Resize the vector to remove the unused elements
    unionSet.resize(it - unionSet.begin());
  
    // Print the union set
    cout << "Union of set1 and set2 ";
    cout << endl;
    for (int element : unionSet) {
        cout << element << " ";
    }
  
    return 0;
}


Output

Union of set1 and set2 
11 12 13 14 15 16 17 18 

Time Complexity : O(n + m), where n is the size of set1, and m is the size of set2.
Space Complexity : O(n + m)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads