7.8. Performing Set Operations on Sequences


You have sequences that you want to rearrange using set operations like union, difference, or intersection.


Use the standard library functions built for exactly this purpose: set_union , set_dif-ference , and set_intersection . Each of these performs its respective set operation and places the results in an output range. See how to do this in Example 7-8.

Example 7-8. Using set operations

#include <iostream>
#include <algorithm>
#include <string>
#include <set>
#include <iterator>
#include "utils.h" // For printContainer(): see 7.10

using namespace std;

int main() {

   cout << "Enter some strings: ";
   istream_iterator<string> start(cin);
   istream_iterator<string> end;
   set<string> s1(start, end);


   cout << "Enter some more strings: ";
   set<string> s2(++start, end);

   set<string> setUnion;
   set<string> setInter;
   set<string> setDiff;

   set_union(s1.begin(), s1.end(),
             s2.begin(), s2.end(),
             inserter(setUnion, setUnion.begin()));

   set_difference(s1.begin(), s1.end(),
                  s2.begin(), s2.end(),
                  inserter(setDiff, setDiff.begin()));

   set_intersection(s1.begin(), s1.end(),
                    s2.begin(), s2.end(),
                    inserter(setInter, setInter.begin()));

   cout << "Union:\n";
   cout << "Difference:\n";
   cout << "Intersection:\n";

The output to this program looks like this (printContainer just prints the contents of a container):

Enter some strings: a b c d ^Z Enter some more strings: d e ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.