Click to See Complete Forum and Search --> : stl newbie, set intersection of two sets into another set


Yves M
October 7th, 2002, 11:56 AM
It's pretty simple, I'd like to put the intersection of two sets into another set. The problem I have is with the output iterator. I don't know how to define one for std::set :/

Here is my code up to now :

#include <set>
#include <map>
#include <algorithm>

using namespace std;

int main()
{
set<long> Source, Target, Intersection

Source.insert(10);
Source.insert(20);
Target.insert(5);
Target.insert(10);
set_intersection(Source.begin(), Source.end(), Target.begin(), Target.end(), ???);
return 0;
}

Unfortunately the examples I found on my standard reference site all use the algorithms for C style arrays and the output iterator is always an ostream :/

Yves M
October 7th, 2002, 12:08 PM
Ok, I got it :rolleyes:


#include <set>
#include <map>
#include <algorithm>

using namespace std;

int main()
{
set<long> Source, Target, Intersection
insert_iterator<set<long> > ii(Intersection, Intersection.begin());

Source.insert(10);
Source.insert(20);
Target.insert(5);
Target.insert(10);
set_intersection(Source.begin(), Source.end(), Target.begin(), Target.end(), ii);
return 0;
}

jwbarton
October 7th, 2002, 01:53 PM
Or without the extra variable:


set_intersection( Source.begin(), Source.end(), Target.begin(), Target.end(), inserter(Intersection,Intersection.begin()) );


Best regards,
John

Yves M
October 7th, 2002, 02:40 PM
Interesting, thanks :)