In-place C++ set intersection

前端 未结 3 1597
南方客
南方客 2020-12-28 17:39

The standard way of intersecting two sets in C++ is to do the following:

std::set set_1;  // With some elements
std::set set_2;  // Wit         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-28 18:18

    It's not directly answers the question, but maybe someone find this helpful.

    In case of std::vector it is not safe to use standard algorithm with set_1.begin() as output iterator (see below), while clang/gcc/microsoft implementations would work. Note, set_2 could be anything, not just a std::vector.

    std::vector set_1;  // With some elements
    std::vector set_2;  // With some other elements
    auto end = std::set_intersection(
                         set_1.begin(), set_1.end(), 
                         set_2.begin(), set_2.end(), 
                         set_1.begin() // intersection is written in set_1
                        );
    set_1.erase(end, set_1.end()); // erase redundant elements
    

    Update:

    Thanks to @Keith who found that C++ Standard (25.4.5.3) requires next:

    The resulting range shall not overlap with either of the original ranges
    

    So what I initially proposed was wrong, but working solution in major STL implementations. If you want to be on safe side and don't want extra allocations then copy implementation of your choice to you code base and use it instead of std::set_intersection. I don't really understand reasons for such restriction, please comment if you know the answer.

提交回复
热议问题