In C++, you can find the intersection of two sets using the set_intersection algorithm from the
In this example,
set1
and set2
, as arrays.std::sort
function.intersection
to store the intersection of the two sets.std::set_intersection
algorithm to find the intersection of set1
and set2
, storing the result in intersection
.intersection
to display the intersection of the two sets.#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> set1 = {1, 2, 3, 4};
std::vector<int> set2 = {3, 4, 5, 6};
std::vector<int> intersection(set1.size() + set2.size());
std::sort(set1.begin(), set1.end());
std::sort(set2.begin(), set2.end());
auto it = std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), intersection.begin());
intersection.resize(it - intersection.begin());
std::cout << "Intersection of set1 and set2:\n";
for (int i : intersection) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Intersection of set1 and set2: 3 4
In this example,
set1
and set2
, as arrays.std::sort
function.intersection
to store the intersection of the two sets.std::set_intersection
algorithm to find the intersection of set1
and set2
, storing the result in intersection
.intersection
to display the intersection of the two sets.#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> set1 = {1, 2, 2, 3, 4};
std::vector<int> set2 = {2, 2, 3, 4, 5};
std::vector<int> intersection(std::min(set1.size(), set2.size()));
std::sort(set1.begin(), set1.end());
std::sort(set2.begin(), set2.end());
auto it = std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), intersection.begin());
intersection.resize(it - intersection.begin());
std::cout << "Intersection of set1 and set2 with duplicates:\n";
for (int i : intersection) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
Intersection of set1 and set2 with duplicates: 2 2 3 4
In this tutorial, we learned How to find Intersection of Two Sets in C++ language with well detailed examples.