Performing set_difference on unordered sets

谁说胖子不能爱 提交于 2020-08-04 09:22:27

问题


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?


回答1:


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(); });



回答2:


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



来源:https://stackoverflow.com/questions/22710331/performing-set-difference-on-unordered-sets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!