The fastest way to find union of sets

后端 未结 7 559
说谎
说谎 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:21

    I assume with fast you mean fast to implement.

    Then: std::set_union (*)

    Example for two sets:

    #include 
    #include 
    #include 
    using namespace std;
    
    int main () {
        set > a, b, uni;
        set_union (a.begin(), a.end(),
                   b.begin(), b.end(),
                   inserter(uni, uni.begin()));
    
    }
    

    for n sets, hand writing it might be the most maintainable solution:

    #include 
    #include 
    using namespace std;
    
    int main () {
        vector>> sets;
        set> uni;
    
        for (const auto &s : sets)
            for (const auto &elem : s)
                uni.insert (elem);
    }
    

    though in general, one should prefer standard algorithms and profit from their quality implementation.

    If by fast you mean performance, we can't help as we don't have the requirements. Different approaches might give different results for different circumstances.


    (*) note: the site is frowned upon sometimes for not being 100% accurate vs. the standard

提交回复
热议问题