How to do intersection and union for sets of the type tr1::unordered_set in c++? I can't find much reference about it.
Any reference and code will be highly appreciated. Thank you very much.
Update: I just guessed the tr1::unordered_set should provide the function for intersection, union, difference.. Since that's the basic operation of sets. Of course I can write a function by myself, but I just wonder if there are built in function from tr1. Thank you very much.
based on the previous answer: C++11 version, if the set supports a fast look up function
find()
(return values are moved efficiently)There's nothing much to it - for intersect, just go through every element of one and ensure it's in the other. For union, add all items from both input sets.
For example:
I see that
set_intersection()
et al. from thealgorithm
header won't work as they explicitly require their inputs to be sorted -- guess you ruled them out already.It occurs to me that the "naive" approach of iterating through hash A and looking up every element in hash B should actually give you near-optimal performance, since successive lookups in hash B will be going to the same hash bucket (assuming that both hashes are using the same hash function). That should give you decent memory locality, even though these buckets are almost certainly implemented as linked lists.
Here's some code for
unordered_set_difference()
, you can tweak it to make the versions for set union and set difference:Assuming you have two
unordered_set
s,x
andy
, you can put their intersection inz
using:Unlike bdonlan's answer, this will actually work for any key types, and any combination of container types (although using
set_intersection()
will of course be faster if the source containers are sorted).NOTE: If bucket occupancies are high, it's probably faster to copy each hash into a
vector
, sort them andset_intersection()
them there, since searching within a bucket containing n elements is O(n).