I know the STL has set_difference
, but I need to just know if 2 set
s are disjoint. I've profiled my code and this is slowing my app down quite a bit. Is there an easy way to see if 2 sets are disjoint, or do I need to just roll my own code?
EDIT: I also tried set_intersection
but it took the same time...
Modified hjhill's code to reduce complexity by a factor of O(log n) by getting rid of the count() call.
template<class Set1, class Set2>
bool is_disjoint(const Set1 &set1, const Set2 &set2)
{
if(set1.empty() || set2.empty()) return true;
typename Set1::const_iterator
it1 = set1.begin(),
it1End = set1.end();
typename Set2::const_iterator
it2 = set2.begin(),
it2End = set2.end();
if(*it1 > *set2.rbegin() || *it2 > *set1.rbegin()) return true;
while(it1 != it1End && it2 != it2End)
{
if(*it1 == *it2) return false;
if(*it1 < *it2) { it1++; }
else { it2++; }
}
return true;
}
I've complied and tested this code now so it should be good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With