set_intersection in C++

In python if we want to get the intersection of two sets, we can simply write the code of s1 & s2

In C++, set is sorted. It seems that we can not find a short way to implement the intersection of two unordered_sets. Details can be found here.

However, for the set, which is sorted, we can use the set_intersection to get the intersection of two sorted containers.

Example 1[1]

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v1{1,2,3,4,5,6,7,8};
std::vector<int> v2{ 5, 7, 9,10};
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());

std::vector<int> v_intersection;

std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(v_intersection));
for(int n : v_intersection)
std::cout << n << ' ';
}

Output

5 7

Example 2

See my previous post HERE.

Example 3[2]

// set_intersection example
#include <iostream> // std::cout
#include <algorithm> // std::set_intersection, std::sort
#include <vector> // std::vector

int main () {
int first[] = {5,10,15,20,25};
int second[] = {50,40,30,20,10};
std::vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0
std::vector<int>::iterator it;

std::sort (first,first+5); // 5 10 15 20 25
std::sort (second,second+5); // 10 20 30 40 50

it=std::set_intersection (first, first+5, second, second+5, v.begin());
// 10 20 0 0 0 0 0 0 0 0
v.resize(it-v.begin()); // 10 20

std::cout << "The intersection has " << (v.size()) << " elements:\n";
for (it=v.begin(); it!=v.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}

Output

The intersection has 2 elements:
10 20

Reference

[1]https://en.cppreference.com/w/cpp/algorithm/set_intersection

[2]http://www.cplusplus.com/reference/algorithm/set_intersection/

Data Scientist/MLE/SWE @takemobi