std::set_intersection and iterators

Viewed 87

Is it possible to have the output of std::set_intersection or other std::set_* algorithmic functions be added directly to a type std::set?

So far, I can only think of a way to add directly to something that allows std::back_inserter.

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

int main()
{
   // sorted so ok for set operations
   set<int> s = { 2, 3, 1 };
   set<int> s2 = { 1 };
   vector<int> v;

   set_intersection(s.begin(), s.end(), s2.begin(), s2.end(),
      back_inserter(v));

   copy(v.begin(), v.end(), ostream_iterator<int>(cout, ","));
   return 0;
}
2 Answers

Yes, You can use std::inserter, instead of the std::back_inserter like this.

#include <iterator> // std::inserter

std::set<int> s3;
std::set_intersection(s.begin(), s.end(), s2.begin(), s2.end(),
      std::inserter(s3, s3.end()));
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Yes, just use inserter instead of back_inserter

set<int> s = {2, 3, 1};
set<int> s2 = {1};
set<int> s3;

set_intersection(s.begin(), s.end(), s2.begin(), s2.end(),
         inserter(s3, s3.end()));
Related