How to Find the Union of Two Sets in C++?
Last Updated :
19 Feb, 2024
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++
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
set< int > set1 = { 11, 12, 13, 14, 15 };
set< int > set2 = { 14, 15, 16, 17, 18 };
vector< int > unionSet(set1.size() + set2.size());
auto it
= set_union(set1.begin(), set1.end(), set2.begin(),
set2.end(), unionSet.begin());
unionSet.resize(it - unionSet.begin());
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)
Share your thoughts in the comments
Please Login to comment...