Algorithm Set Union Function - C++ Programming Tutorial
C++ Course / STL Set & Map / Algorithm Set Union Function

Algorithm Set Union Function

BLUF: Mastering Algorithm Set Union Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Set Union Function

C++ is renowned for its efficiency. Learn how Algorithm Set Union Function enables low-level control and high-performance computing in the tutorial below.

The C++ set_union function is employed to determine the union of two sorted intervals [first1, last1) and [first2, last2), consisting of elements existing in either set or both.

Elements are compared utilizing the < operator in the initial version or through the specified binary evaluation function comp in the subsequent version.

Syntax

Example

default (1)     template <class InputIterator1, class InputIterator2, class OutputIterator>
                        OutputIterator set_union (InputIterator1 first1, InputIterator1 last1,
                            InputIterator2 first2, InputIterator2 last2, OutputIterator result);

custom (2)     template <class InputIterator1, class InputIterator2,
                     class OutputIterator, class Compare>
                   OutputIterator set_union (InputIterator1 first1, InputIterator1 last1,
              InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp);

Parameter

An input iterator pointing to the initial element in the first of two sorted origin sequences.

last1: Refers to an input iterator indicating the element after the last element in the initial sorted sequence of the two source sequences.

An initial iterator pointing to the first item in the subsequent sorted origin sequence.

An input iterator pointing to the element just before the final element in the second sorted origin sequence.

A custom binary predicate function named comp is defined by the user. This function takes two arguments and evaluates to true if the arguments are in a specified order, otherwise it returns false. It adheres to the principles of strict weak ordering for arranging the elements.

An output iterator pointing to the location of the initial element in the target range.

Return value

This function provides an iterator pointing to the conclusion of the created range.

Complexity

The time complexity is proportional to the interval's length between [first1, last1) and [first2, last2): executing a maximum of 2*(count1+count2)-1 comparisons. Here, count1 is calculated as last1 - first1, and count2 is determined as last2 - first2.

Data races

The elements within the range [first1, last1) and [first2, last2) are both accessed.

The items within the range from the result to the output value are altered.

Exceptions

This function will raise an exception if any error occurs during element comparison, element assignments, or iterator operation.

Note: The invalid parameters cause an undefined behavior.

Example 1

Let's examine a basic example to showcase the functionality of set_union:

Example

#include <iostream>
#include <set>
#include <list>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
  list<int> a = {1, 2, 3, 4};
  multiset<int> b = {4, 5, 6, 2};
  vector<int> result;

  set_union(begin(a), end(a),
                 begin(b), end(b),
                 inserter(result, end(result)));

  for_each(begin(result), end(result), [](int x) {
    cout << x << endl;
  });
  
  return 0;
}

Output:

Output

1
2
3
4
5
6

Example 2

Let's see another simple example:

Example

#include <iostream>     // std::cout
#include <algorithm>    // std::set_union, std::sort
#include <vector>       // std::vector

using namespace std;

int main() 
{ 
    int first[] = { 5, 10, 15, 20, 25 }; 
    int second[] = { 50, 40, 30, 20, 10 }; 
    int n = sizeof(first) / sizeof(first[0]); 
  
    // Print first array 
    cout << "First array contains:"; 
    for (int i = 0; i < n; i++) 
        cout << " " << first[i]; 
    cout << "\n"; 
  
    // Print second array 
    cout << "Second array contains:"; 
    for (int i = 0; i < n; i++) 
        cout << " " << second[i]; 
    cout << "\n\n"; 
  
    vector<int> v(10); 
    vector<int>::iterator it, st; 
  
    sort(first, first + n); 
    sort(second, second + n); 
  
    // Using default function 
    it = set_union(first, first + n, second, second + n, v.begin()); 
  
    cout << "The union has " << (it - v.begin()) << " elements:\n"; 
    for (st = v.begin(); st != it; ++st) 
        cout << ' ' << *st; 
    cout << '\n'; 
  
    return 0; 
}

Output:

Output

First array contains: 5 10 15 20 25
Second array contains: 50 40 30 20 10

The union has 8 elements:
 5 10 15 20 25 30 40 50

Example 3

Let's explore another straightforward example to identify the roster of students enrolled in both courses:

Example

#include <iostream> 
#include <algorithm> 
#include <vector> 
#include <string> 
  
using namespace std; 
  
// Driver code 
int main() 
{ 
    string first[] = { "Nikita", "Divya", "Deep", "Kashish" }; 
    string second[] = { "Aman", "Nikita", "Amita", "Deep" }; 
    int n = sizeof(first) / sizeof(first[0]); 
  
    // Print students of first list 
    cout << "Students in first subject:"; 
    for (int i = 0; i < n; i++) 
        cout << " " << first[i]; 
    cout << "\n"; 
  
    // Print students of second list 
    cout << "Students in second subject:"; 
    for (int i = 0; i < n; i++) 
        cout << " " << second[i]; 
    cout << "\n\n"; 
  
    vector<string> v(10); 
    vector<string>::iterator it, st; 
  
    // Sorting both the list 
    sort(first, first + n); 
    sort(second, second + n); 
  
    // Using default operator< 
    it = set_union(first, first + n, second, second + n, v.begin()); 
  
    cout << "Students attending both subjects are:\n"; 
    for (st = v.begin(); st != it; ++st) 
        cout << ' ' << *st; 
    cout << '\n'; 
  
    return 0; 
}

Output:

Output

Students in first subject: Nikita Divya Deep Kashish
Students in second subject: Aman Nikita Amita Deep

Students attending both subjects are:
 Aman Amita Deep Divya Kashish Nikita

Example 4

Let's see a simple example:

Example

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

using namespace std;
 
int main()
{ 
    vector<char> v1 = {'A', 'B', 'C'}; 
    vector<char> v2 = {      'C', 'D', 'E', 'F'}; 
    
    vector<char> dest1;
 
    set_union(v1.begin(), v1.end(),
                   v2.begin(), v2.end(),                  
                   back_inserter(dest1));
 
    for (const auto &i : dest1) {
        cout << i << ' ';
    }   
    cout << '\n';
    
    return 0;
}

Output:

Output

A B C D E F

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience