7.8. Performing Set Operations on Sequences

Problem

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

Solution

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

   cin.clear();

   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";
   printContainer(setUnion);
   cout << "Difference:\n";
   printContainer(setDiff);
   cout << "Intersection:\n";
   printContainer(setInter);
}

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.