Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page