Apache C++ Standard Library Reference Guide

## set_union()

Library:  Algorithms

`Function`

No Entries

### Summary

A basic set operation (algorithm) for constructing a sorted union

### Synopsis

```#include <algorithm>

namespace std {
template <class InputIterator1, class InputIterator2,
class OutputIterator>
OutputIterator
set_union(InputIterator1 start1, InputIterator1 finish1,
InputIterator2 start2, InputIterator2 finish2,
OutputIterator result);

template <class InputIterator1, class InputIterator2,
class OutputIterator, class Compare>
OutputIterator
set_union(InputIterator1 start1, InputIterator1 finish1,
InputIterator2 start2, InputIterator2 finish2,
OutputIterator result, Compare comp);
}
```

### Description

The set_union() algorithm constructs a sorted union of the elements from the two ranges. It returns the end of the constructed range. set_union() is stable, which means that if an element is present in both ranges, the one from the first range is copied. The result of set_union() is undefined if the result range overlaps with either of the original ranges. Note that set_union() does not merge the two sorted sequences. If an element is present in both sequences, only the element from the first sequence is copied to result. (Use the merge() algorithm to create an ordered merge of two sorted sequences that contains all the elements from both sequences.)

set_union() assumes that the sequences are sorted using operator<(), unless an alternative comparison function object (comp) is provided.

### Complexity

At most ((finish1 - start1) + (finish2 - start2)) * 2 -1 comparisons are performed.

### Example

```//
//  set_unin.cpp
//

#include <algorithm>
#include <set>
#include <iostream>

int main ()
{
_USING (namespace std);

typedef set<int, less<int>,allocator<int> > Set;

// Initialize sets.

int a1[] = {2, 4, 6, 8, 10, 12};
int a2[] = {3, 5, 7, 8};

Set s1 (a1, a1 + sizeof a1 / sizeof *a1);
Set s2 (a2, a2 + sizeof a2 / sizeof *a2);
Set result;

// Create an insert_iterator for result.

insert_iterator<Set> res_ins (result, result.begin ());

// Compute union of two sets.

set_union (s2.begin (), s2.end (),
s1.begin (), s1.end (), res_ins);

// Display result on standard output.

typedef ostream_iterator<int, char, char_traits<char> >
OSIter;

cout << "The result of:" << endl << "{ ";
copy (s2.begin (),s2.end (), OSIter (cout," "));
cout << "} union { ";
copy (s1.begin (),s1.end (), OSIter (cout," "));
cout << "} =" << endl << "{ ";
copy (result.begin (),result.end (), OSIter (cout," "));
cout << "}" << endl << endl;

return 0;
}

Program Output:
```
```The result of:
{ 3 5 7 8 } union { 2 4 6 8 10 12 } =
{ 2 3 4 5 6 7 8 10 12 }

```