要确定两个集合(给定为std::set
)是否不相交,您可以简单地计算它们的交集:
std::set<T> X, Y; // populate
std::set<T> I;
std::set_difference(X.begin(), X.end(), y.begin(), y.end(), std::back_inserter(I));
const bool disjoint = I.empty();
如果你的容器不是std::set
s,你必须确保范围是有序的。
如果你想提高效率,你可以实现算法,set_intersection
一旦你有一个共同的元素就停止:
template <typename Iter1, typename Iter2>
bool disjoint(Iter1 first1, Iter1 last1, Iter2 first2, Iter2 last2)
{
while (first1 != last1 && first2 != last2)
{
if (*first1 < *first2) ++first1;
else if (*first2 < *first1) ++first2;
else { return false; }
}
return true;
}