I have been given two sets (std :: set from <set> ), from which I would like to know the size of the intersection. I could use std :: set_intersection from <algorithm> , but I have to provide it with an output iterator to copy the intersection into another container.
A simple way would be
set<int> s1{1,2,3,4,5}; set<int> s2{4,5,6,7,8,9,0,1}; vector<int> v; set_intersection( s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(v, v.begin()));
after which v.size () sets the size of the intersection. However, the intersection must be preserved, even if we do not do anything with it.
To avoid this, I tried to implement a dummy iterator output class, which only counts, but it does not assign:
template<typename T> class CountingOutputIterator { private: int* counter_; T dummy_; public: explicit CountingOutputIterator(int* counter) :counter_(counter) {} T& operator*() {return dummy_;} CountingOutputIterator& operator++() {
with which we could do
set<int> s1{1,2,3,4,5}; set<int> s2{4,5,6,7,8,9,0,1}; int counter = 0; CountingOutputIterator<int> counter_it(&counter); set_intersection( s1.begin(), s1.end(), s2.begin(), s2.end(), counter_it);
after which the counter has the size of the intersection.
This is much more code. My questions:
1) Is there a standard (library) way or a standard trick to get the size of the intersection without saving the entire intersection? 2) Whether or not it exists, is the approach with a custom dummy iterator good?