From the title you’d almost assuredly think use set_union to create a list and then check if it’s empty. However, the objects I’m comparing are “expensive” to copy. I’ve looked at includes but that only works if all the items of one list are found in another. I’ve also looked at mismatch but rejected it for obvious reasons.
I can and have written my own function which assumes both lists are sorted but I’m wondering if an efficient function already exists in the STL. (Project is forbidden to use third-party libraries including Boost and TR1, don’t ask.)
If the sets are unsorted, then you can use
find_first_offor an O(N*M) algorithm.If they are sorted (which would be required for
set_intersectionanyway), then you can iterate over one set callingequal_rangein the other for every element. If every returned range is empty, there is no intersection. Performance is O(N log M).However, there is no excuse not to have O(N+M) performance, right? Nothing is copied by
set_intersectionif it’s passed a dummy iterator.This provides for early exit. You could alternately avoid the exception and just have the iterator remember how many times it was incremented, and no-op the assignment.