Nikos Athanasiou
Nikos Athanasiou

Reputation: 31549

Performing set_difference on unordered sets

The set_difference algorithm requires the following

The elements in the ranges shall already be ordered according to this same criterion

which is not the case for hash tables.

I'm thinking of implementing a set difference A-B in terms of std::remove_copy where the removal criterion would be the existence of an element of A in the set B.

Is there a standard-valid-fastest-safest way to do it?

Upvotes: 12

Views: 10414

Answers (2)

CashCow
CashCow

Reputation: 31445

If you have 2 unordered sets A and B of length Na and Nb and you want to do a set-difference, i.e. get all elements of A not in B, then as the look-up in B is constant time, your complexity of simply iterating over A and checking if it is in B is O(Na).

If A is an unordered set and B is a set (or sorted vector etc) then each lookup would be log(Nb) so the full complexity would be O(Na*log(Nb))

Sorting A first would make it (Na * log(Na)) to sort then Na+Nb to do the merge. If Na is significantly smaller than Nb then Na*log(Nb) is significantly smaller than Na+Nb anyway and if Na is getting larger towards Nb then sorting it first isn't going to be any quicker.

Therefore I reckon you gain nothing by sorting A first (by sorting it first, I mean moving it to a sorted collection).

Upvotes: 4

John Zwinck
John Zwinck

Reputation: 249444

If you have two hash tables, the most efficient way should be to iterate over one of them, looking up each element in the other hash table. Then insert the ones you do not find into some third container. A rough sketch might look like this:

std::vector<int> result;
std::copy_if(lhs.begin(), lhs.end(), std::back_inserter(result),
    [&rhs] (int needle) { return rhs.find(needle) == rhs.end(); });

Upvotes: 14

Related Questions