CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Aug 2002
    Location
    Madrid
    Posts
    4,588

    stl newbie, set intersection of two sets into another set

    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 :
    Code:
    #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 :/

  2. #2
    Join Date
    Aug 2002
    Location
    Madrid
    Posts
    4,588
    Ok, I got it

    Code:
    #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;
    }

  3. #3
    Join Date
    Jan 2001
    Posts
    253
    Or without the extra variable:

    Code:
    set_intersection( Source.begin(), Source.end(), Target.begin(), Target.end(), inserter(Intersection,Intersection.begin()) );
    Best regards,
    John

  4. #4
    Join Date
    Aug 2002
    Location
    Madrid
    Posts
    4,588
    Interesting, thanks
    Get this small utility to do basic syntax highlighting in vBulletin forums (like Codeguru) easily.
    Supports C++ and VB out of the box, but can be configured for other languages.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured