设置交集和迭代器

Is it possible to have the output of set_intersection or other set_* algorithmic functions be added directly to a type set? So far, I can only think of a way to add directly to something that allows 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;
}
评论
  • 胡了~
    胡了~ 回复

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

    #include <iterator>
    #include <algorithm>
    #include <set>
    
    
    int main() 
    {
       std::set<int> s = { 2, 3, 1 };
       std::set<int> s2 = { 1 };
       std::set<int> s3;
    
       std::set_intersection(s.begin(), s.end(), s2.begin(), s2.end(),
          std::inserter(s3, s3.end()));
       return 0;
    }
    

  • _佐瞧瞧
    _佐瞧瞧 回复

    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));