Click here to Skip to main content
11,706,799 members (47,718 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ ATL WTL STL
How to compute difference and intersection of two sets?
There are functions set_difference and set_intersection which requires two pairs of iterators of source sets and output iterator of resulting set. Here, set can be any sorted container with incrementable iterator. There is another requirement that the output should be large enough to contain the destination range.
For STL-set, however, you cannot set the size of it and using an empty set as output leads to assertion. In fact, output iterator of destination empty set is equal to end() and incrementing iterator does not add elements to a set.
So how to compute this?
Posted 21-Apr-09 23:03pm
liquid_569

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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 <span class="code-keyword"><vector></span>
#include <span class="code-keyword"><set></span>
#include <span class="code-keyword"><iostream></span>
#include <span class="code-keyword"><algorithm></span>
#include <span class="code-keyword"><iterator></span>

int main()
{
   std::set<int> a, b, c;
   a.insert(1);
   a.insert(2);
   a.insert(3);
   a.insert(4);
   b.insert(2);
   b.insert(4);
   b.insert(5);
   b.insert(7);
   std::vector<int> d;

   std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(c, c.end()));
   std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(d));
   
   std::copy(c.begin(), c.end(), std::ostream_iterator<int>(std::cout, " "));
   std::copy(d.begin(), d.end(), std::ostream_iterator<int>(std::cout, " "));
}


  Permalink  
  Print Answers RSS
0 OriginalGriff 156
1 Sergey Alexandrovich Kryukov 155
2 chainerlt 110
3 ppolymorphe 91
4 Mika Wendelius 70
0 OriginalGriff 9,190
1 Sergey Alexandrovich Kryukov 8,407
2 CPallini 5,189
3 Maciej Los 4,756
4 Mika Wendelius 3,686


Advertise | Privacy | Mobile
Web03 | 2.8.150819.1 | Last Updated 22 Apr 2009
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100