2

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, ...}
5gon12eder
  • 24,280
  • 5
  • 45
  • 92
Striker
  • 507
  • 4
  • 11
  • Did you have a look at `std::set` already? – πάντα ῥεῖ Aug 16 '15 at 11:35
  • 2
    The answer by @bigOTHER is correct, but was this question a "howto" question or an algorithmic one? (if it's algorithmic, and the sets are ordered, then http://stackoverflow.com/questions/5958169/how-to-merge-two-sorted-arrays-into-a-sorted-array). – shapiro yaacov Aug 16 '15 at 11:51

2 Answers2

6

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
Assem
  • 11,574
  • 5
  • 59
  • 97
1

Use std::set_intersection as described here:

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

  • 3
    When looking up C++ documentation I prefer [cppreference.com](http://en.cppreference.com/w/cpp) to [www.cplusplus.com](http://www.cplusplus.com) since the first is more often correct than the latter. –  Aug 16 '15 at 11:45
  • Thanks, I will remember this. – jan_kowalski_314 Aug 16 '15 at 11:57