how to find the intersection of two std::set in C++?

ILikeTacos picture ILikeTacos · Nov 19, 2012 · Viewed 79.2k times · Source

I have been trying to find the intersection between two std::set in C++, but I keep getting an error.

I created a small sample test for this

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;

int main() {
  set<int> s1;
  set<int> s2;

  s1.insert(1);
  s1.insert(2);
  s1.insert(3);
  s1.insert(4);

  s2.insert(1);
  s2.insert(6);
  s2.insert(3);
  s2.insert(0);

  set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end());
  return 0;
}

The latter program does not generate any output, but I expect to have a new set (let's call it s3) with the following values:

s3 = [ 1 , 3 ]

Instead I'm getting the error:

test.cpp: In function ‘int main()’:
test.cpp:19: error: no matching function for call to ‘set_intersection(std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>)’

What I understand out of this error, is that there's no definition in set_intersection that accepts Rb_tree_const_iterator<int> as parameter.

Furthermore, I suppose the std::set.begin() method returns an object of such type,

is there a better way to find the intersection of two std::set in C++? Preferably a built-in function?

Thanks a lot!

Answer

Karthik T picture Karthik T · Nov 19, 2012

You havent provided an output iterator for set_intersection

template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_intersection ( InputIterator1 first1, InputIterator1 last1,
                                InputIterator2 first2, InputIterator2 last2,
                                OutputIterator result );

Fix this by doing something like

...;
set<int> intersect;
set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),
                  std::inserter(intersect,intersect.begin()));

You need a std::insert iterator since the set is as of now empty. We cannot use back_ or front_inserter since set doesnt support those operations.