c++algorithmstlsetset-intersection

How do I find the intersection of 2 sets?


What is the most efficient way to create a subset from 2 sets that contains values from both of them? Any C++ STL library can be used to solve this (without Boost library if possible):

Set A = {2, 3, 5, 7, 11, ...}
Set B = {1, 3, 5, 7, 9, 11, ...}

Subset should be = {3, 5, 7, 11, ...}

Solution

  • You can do it by using set_intersection, you will find an example there how to use it:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <iterator>
    int main()
    {
        std::vector<int> v1{2, 3, 5, 7, 11};;
        std::vector<int> v2{1, 3, 5, 7, 9, 11};
        std::sort(v1.begin(), v1.end());
        std::sort(v2.begin(), v2.end());
    
        std::vector<int> v_intersection;
    
        std::set_intersection(v1.begin(), v1.end(),
                              v2.begin(), v2.end(),
                              std::back_inserter(v_intersection));
        for(int n : v_intersection)
            std::cout << n << ' ';
    }
    

    Results will be:

     3 5 7 11