The fastest way to find union of sets

后端 未结 7 596
说谎
说谎 2021-01-11 09:39

I have sets of pairs of int like set > x1, x2, ... xn ( n can be between 2 and 20). What is the fastest way to find union of those se

7条回答
  •  无人及你
    2021-01-11 10:26

    To save on memory allocations and improve locality, it'd be better to use a single vector as working memory.

    Construct a vector and reserve the total number of elements in all of the s (counting duplicates). Then, starting with the empty range [v.begin(), v.begin()), extend it to a set-like (unique, sorted) range by appending the contents of each set, merging and uniquifying:

    vector v;
    v.reserve();
    for (set &s: sets) {
        auto middle = v.insert(v.end(), s.begin(), s.end());
        inplace_merge(v.begin(), middle, v.end());
        v.erase(v.unique(v.begin(), v.end()), v.end());
    }
    

提交回复
热议问题