How to use the set_union() function in C++

In this shot, we will learn how to use the set_union() function in C++.

The set_union() function is available in the <algorithm> library in C++.

The set_union() function is used to find the union of the two sorted ranges, which is formed only by the elements that are present in both sets.

Syntax

The syntax of the set_union() function is shown below:

OutputIterator set_union(first1, last1, first2, last2, res)

Parameters

The set_union() method takes the following parameters:

  • First1: The input iterator to the initial position of the first sorted sequence.
  • Last1: The input iterator to the final position of the first sorted sequence.
  • First2: The input iterator to the initial position of the second sorted sequence.
  • Last2: The input iterator to the final position of the second sorted sequence.
  • Res: The output iterator to the initial position of the range where the resulting sequence is stored.

Return value

The set_union() function returns an iterator to the end of the constructed range.

Code

Let’s have a look at the code below:

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int first[] = { 25, 110, 105, 120, 125 };
int second[] = { 150, 120, 105, 225, 25 };
int n = sizeof(first) / sizeof(first[0]);
cout << "First array contains :";
for (int i = 0; i < n; i++)
cout << " " << first[i];
cout << "\n";
cout << "Second array contains :";
for (int i = 0; i < n; i++)
cout << " " << second[i];
cout << "\n\n";
vector<int> v(10);
vector<int>::iterator it1, st1;
sort(first, first + n);
sort(second, second + n);
it1 = set_union(first, first + n, second, second + n, v.begin());
cout << "The union has " << (it1 - v.begin())<< " elements:\n";
for (st1 = v.begin(); st1 != it1; ++st1)
cout << ' ' << *st1;
cout << '\n';
return 0;
}

Explanation:

  • In lines 1 to 3, we imported the required header files.

  • In line 6, we made a main() function.

  • In line 9 and 10, we initialized two arrays.

  • From lines 13 to 15, we displayed the elements of the first array.

  • From lines 18 to 20, we displayed the elements of the second array.

  • In line 23, we declared a vector of int type.

  • In line 24, we declared two iterators to a vector of int type.

  • In lines 26 and 27, we sorted the two arrays.

  • In line 29, we used the set_union() function to obtain the union and store the output vector’s initial position in the iterator.

  • In line 31, we displayed the number of elements in the union.

  • From lines 32 to 33, we displayed the elements of union using the iterator and loop.

So, this is how to use the set_union() function in C++.

Free Resources