set_union |
Create a set of elements that are in either sequence.
Place the sorted union of all the
elements in the sequences [ first1...last1 ) and [
first2...last2 ) into a sequence starting at result
. Return an iterator positioned immediately after the end of the new sequence.
The result is undefined if the two input sequences overlap. If an element occurs
in both sequences, the element from the first sequence is copied into the result
sequence. The first version assumes that both sequences are already sorted using
operator< , whereas the second version assumes
that both sequences are already sorted using the binary function compare
.
#include <algorithm>
template
<
class InputIterator1,
class InputIterator2,
class OutputIterator
>
OutputIterator set_union
(
InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result
);
template
<
class InputIterator1,
class InputIterator2,
class OutputIterator,
class Compare
>
OutputIterator set_union
(
InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
InputIterator2 last2,
OutputIterator result,
Compare compare
);
Time complexity is linear. Space complexity is constant.
#include <iostream>
#include <algorithm>
int v1[ 3 ] = { 13, 18, 23 };
int v2[ 4 ] = { 10, 13, 17, 23 };
int result[ 7 ] = { 0, 0, 0, 0, 0, 0, 0 };
void
main()
{
set_union
(
v1,
v1 + 3,
v2,
v2 + 4,
result
);
for ( int i = 0; i < 7; ++i )
cout << result[ i ] << ` `;
cout << "\n";
}
10 13 17 18 23 0 0
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
void
main()
{
vector< int > v1( 10 );
vector< int > v2( 10 );
for ( int i = 0; i < v1.size(); ++i )
{
v1[ i ] = i;
v2[ i ] = 7 + i;
}
ostream_iterator< int > iter( cout, " " );
cout << "v1: ";
copy( v1.begin(), v1.end(), iter );
cout << "\nv2: ";
copy( v2.begin(), v2.end(), iter );
cout << "\n";
set_union( v1.begin(), v1.end(), v2.begin(), v2.end(), iter );
cout << "\n";
}
v1: 0 1 2 3 4 5 6 7 8
v2: 7 8 9 10 11 12 13 14 15 16
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <string.h>
#include <algorithm>
#include <functional>
#include <iterator>
char* word1 = "ABCDEFGHIJKLMNO";
char* word2 = "LMNOPQRSTUVWXYZ";
void
main()
{
ostream_iterator< char > iter( cout, " " );
cout << "word1: ";
copy( word1, word1 + ::strlen( word1 ), iter );
cout << "\nword2: ";
copy( word2, word2 + ::strlen( word2 ), iter );
cout << "\n";
set_union
(
word1,
word1 + ::strlen( word1 ),
word2,
word2 + ::strlen( word2 ),
iter,
less< char >()
);
cout << "\n";
}
word1: A B C D E F G H I J K L M N O
word2: L M N O P Q R S T U V W X Y Z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.