Standard C++ Library User Guide and Tutorial
Click on the banner to return to the user guide home page.
©Copyright 1996 Rogue Wave Software
Set Operations
The operations of set union, set intersection, and set difference were all described in Chapter 7 (Set
Operations) when we discussed the set container class. However, the algorithms that implement
these operations are generic, and applicable to any ordered data structure. The algorithms assume
the input ranges are ordered collections that represent multisets; that is, elements can be repeated.
However, if the inputs represent sets, then the result will always be a set. That is, unlike the
merge() algorithm, none of the set algorithms will produce repeated elements in the output that
were not present in the input sets.
The set operations all have the same format. The two input sets are specified by pairs of input
iterators. The output set is specified by an input iterator, and the end of this range is returned as the
result value. An optional comparison operator is the final argument. In all cases it is required that
the output sequence not overlap in any manner with either of the input sequences.
OutputIterator set_union
(InputIterator first1, InputIterator last1,
InputIterator first2, InputIterator last2,
OutputIterator result [, Compare ] );
The example program illustrates the use of the four set algorithms, set_union, set_intersection,
set_difference and set_symmetric_difference. It also shows a call on merge() in order to contrast
the merge and the set union operations. The algorithm includes() is slightly different. Again the
two input sets are specified by pairs of input iterators, and the comparison operator is an optional
fifth argument. The return value for the algorithm is true if the first set is entirely included in the
second, and false otherwise.
void set_example ()
// illustrate the use of the generic set algorithms
{
ostream_iterator<int> intOut (cout, " ");
// make a couple of ordered lists
list<int> listOne, listTwo;
generate_n (inserter(listOne, listOne.begin()), 5, iotaGen(1));
generate_n (inserter(listTwo, listTwo.begin()), 5, iotaGen(3));
// now do the set operations
// union - 1 2 3 4 5 6 7










