This simple algorithm should do this:
Features:
- complexity: no more than K = max (N, M) iterations, where N is the distance (first1, last1), and M is the distance (first2, last2)
- short circuits
- works with any sorted range
- can replace the predicate
#include <set> #include <ciso646> #include <iostream> #include <cassert> #include <functional> template<class I1, class I2, class Comp = std::less<> > bool has_element_in_common(I1 first1, I1 last1, I2 first2, I2 last2, Comp&& comp = Comp()) { while (first1 != last1 and first2 != last2) { if (comp(*first1, *first2)) { ++first1; } else if (comp(*first2, *first1)) { ++first2; } else { return true; } } return false; } int main() { auto s1 = std::set<int> { 1, 3, 5, 7, 9 }; auto s2 = std::set<int> { 2, 3, 4, 6, 8 }; assert(has_element_in_common(begin(s1), end(s1), begin(s2), end(s2))); auto s3 = std::set<int> { 2, 4, 6, 8 }; assert(!has_element_in_common(begin(s1), end(s1), begin(s3), end(s3))); }
This will require a little work if you want to optimize it to skip duplicates in multisets.
source share