forked from Bhupesh-V/30-seconds-of-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set_intersection.cpp
37 lines (30 loc) · 1.01 KB
/
set_intersection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
Author : Thamara Andrade
Date : Date format 02/09/2019
Time : Time format 02:00
Description : Computes the intersection of two ranges.
*/
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v1 {3, 1, 5};
std::vector<int> v2 {1, 0};
// the destination needs to fit all merged values, we'll prune the extra elements later
std::vector<int> destination(v1.size() + v2.size());
// set_union requires sorted ranges
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
// returns iterator to the end of the constructed range
auto it = std::set_intersection(v1.begin(), v1.end(), // first range
v2.begin(), v2.end(), // second range
destination.begin());
// prune extra values
destination.resize(it - destination.begin());
// destination is now {1}
for (auto value : destination) {
std::cout << value << " ";
}
return 0;
}