Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing set_difference on unordered sets

Tags:

c++

stl

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?

like image 299
Nikos Athanasiou Avatar asked Mar 28 '14 10:03

Nikos Athanasiou


2 Answers

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(); });
like image 73
John Zwinck Avatar answered Oct 16 '22 01:10

John Zwinck


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).

like image 27
CashCow Avatar answered Oct 16 '22 01:10

CashCow