STL set_intersection() and set container

I try to do a set intersection of two STL set containers and output into an STL set contrainer. I have tried to look around, but STL set data type does not have this kind of function. STL algorithm has set_intersection() (http://www.cplusplus.com/reference/algorithm/set_intersection/). But I cannot use an STL set container as the output for this set_intersection().

Can anyone help me for this problem?

Do I need to use an STL vector container as an temporary output and copy from it to an STL set container?
Last edited on
It's not clear why you don't use std::set and can use std::vector.
And please provide short source code that demonstrates your issue.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
std::set<int> s1;
std::set<int> s2;
std::set<int> intersect;

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

// or

std::set_intersection( s1.begin(), s1.end(), s2.begin(), s2.end(),
    std::inserter( intersect, intersect.begin() ) );

Thanks jsmith.
You codes work.
But when I tried to use set<int>::iterator it; similar to http://www.cplusplus.com/reference/algorithm/set_intersection/, there is a compiler error.
Don't worry. Maybe I just use vectors.
Tried to use a set<int>::iterator for what? The last parameter to set_intersection? Of course you can't.
Because set provides an ordering of elements, you can't use iterators to add elements to the set, as you
could then attempt an insert that would break the ordering constraint. For that reason, set<>::iterator
is a typedef of set<>::const_iterator. That's why I used std::inserter. It does the right thing.
Topic archived. No new replies allowed.