Use
std::inserter[
^] or
std::back_inserter[
^] for the output iterator. That causes the items to be inserted into the container without having to know what size it should be before you've constructed it.
If you're using a vector or list as the output, I'd use std::back_inserter. For a set, std::inserter is required. Here's an example:
#include <vector><br />#include <set><br />#include <iostream><br />#include <algorithm><br />#include <iterator><br /><br />int main()<br />{<br /> std::set<int> a, b, c;<br /> a.insert(1);<br /> a.insert(2);<br /> a.insert(3);<br /> a.insert(4);<br /> b.insert(2);<br /> b.insert(4);<br /> b.insert(5);<br /> b.insert(7);<br /> std::vector<int> d;<br /><br /> std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(c, c.end()));<br /> std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(d));<br /> <br /> std::copy(c.begin(), c.end(), std::ostream_iterator<int>(std::cout, " "));<br /> std::copy(d.begin(), d.end(), std::ostream_iterator<int>(std::cout, " "));<br />}