Striker
Striker

Reputation: 505

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, ...}

Upvotes: 2

Views: 10230

Answers (2)

Assem
Assem

Reputation: 12107

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

Upvotes: 6

jan_kowalski_314
jan_kowalski_314

Reputation: 84

Use std::set_intersection as described here:

http://www.cplusplus.com/reference/algorithm/set_intersection/

Upvotes: 1

Related Questions