
set union、set intersection、set difference の演算については、8.2.7 節で set コンテナクラスの説明の際にすべて説明しました。これらの演算を実装するアルゴリズムは汎用アルゴリズムであり、どんな順序付きデータ構造にも適用することができます。このアルゴリズムは、入力範囲が multiset を表す順序付きコレクションであることを想定しています。つまり、要素が繰り返されるということです。ただし、入力が set を表す場合、結果は常に set です。merge() アルゴリズムとは異なり、set アルゴリズムは、入力 set にない繰り返し要素を出力しません。
set 演算の書式はどれも同じです。2 つの入力 set は、入力反復子の対によって指定されます。出力 set は、入力反復子によって指定され、結果の値としてこの範囲の終わりが返されます。最後の引数は、任意の比較演算子です。いずれの場合でも、いかなる方法でも、出力シーケンスは入力シーケンスとオーバーラップしてはなりません。
OutputIterator set_union (InputIterator first1, InputIterator last1, InputIterator first2, InputIterator last2, OutputIterator result [, Compare ] );
次のプログラム例は、4 つの set アルゴリズム set_union、set_intersection、set_difference、set_symmetric_difference を説明しています。また、マージおよび和集合演算と対照させるために、merge() の呼び出しも引用しています。アルゴリズム includes() は多少異なります。2 つの入力集合は、反復子対によって指定され、比較演算子は 5 番目の任意の引数です。このアルゴリズムの戻り値は、最初の set が第 2 の集合に完全に含まれている場合は true で、そ例外の場合は false です。
void set_example ()
// 汎用 set アルゴリズムの使用方法を説明する
// 完全なソースコードについては alg7.cpp を参照
{
ostream_iterator<int> intOut (cout, " ");
// 1 対の順序リストを作成する
list<int> listOne, listTwo;
generate_n (inserter(listOne, listOne.begin()), 5, iotaGen(1));
generate_n (inserter(listTwo, listTwo.begin()), 5, iotaGen(3));
// 集合演算を実行する
// 和集合 - 1 2 3 4 5 6 7
set_union (listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(), intOut), cout << endl;
// マージ - 1 2 3 3 4 4 5 5 6 7
merge (listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(), intOut), cout << endl;
// 積集合 - 3 4 5
set_intersection (listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(), intOut), cout << endl;
// 差 - 1 2
set_difference (listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(), intOut), cout << endl;
// 対称差 - 1 2 6 7
set_symmetric_difference (listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end(), intOut), cout << endl;
if (includes (listOne.begin(), listOne.end(),
listTwo.begin(), listTwo.end()))
cout << "set is subset" << endl;
else
cout << "set is not subset" << endl;
}