O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required