In C++, you can utilize the std::set container from the Standard Template Library (STL) to represent a set and perform set operations.
In this example,
<set>
header to use the std::set
container from the Standard Template Library (STL).std::set
objects, set1
and set2
, and insert elements into them.std::set
, unionSet
, to store the union of set1
and set2
.std::set_union
algorithm from the STL to find the union of set1
and set2
, and store the result in unionSet
.unionSet
to display the union of the two sets.#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
int main() {
std::set<int> set1 = {1, 2, 3};
std::set<int> set2 = {3, 4, 5};
std::set<int> unionSet;
std::set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(unionSet, unionSet.begin()));
std::cout << "Union of set1 and set2:\n";
for (int num : unionSet) {
std::cout << num << " ";
}
return 0;
}
Union of set1 and set2: 1 2 3 4 5
In this example,
std::set
objects, set1
and set2
, to represent the sets.unionSets
that takes references to set1
and set2
as parameters.unionSets
function, we iterate over each element of set2
and insert it into set1
if it's not already present.unionSets
function with set1
and set2
.set1
to display the union set.#include <iostream>
#include <set>
void unionSets(std::set<int>& set1, const std::set<int>& set2) {
for (int num : set2) {
set1.insert(num);
}
}
int main() {
std::set<int> set1 = {1, 2, 3};
std::set<int> set2 = {3, 4, 5};
unionSets(set1, set2);
std::cout << "Union of set1 and set2:\n";
for (int num : set1) {
std::cout << num << " ";
}
return 0;
}
Union of set1 and set2: 1 2 3 4 5
In this tutorial, we learned How to find Union of Two Sets in C++ language with well detailed examples.