Finding Union of Two Vectors in C++

To find the union of two vectors in C++, we can use the std::set_union function provided by STL which can be used to find the union of two sorted ranges. So first, we have to sort both the vectors.

Syntax of std::set_union()

set_union (first1, last1, first2, last2, result);

where,

  • first1: Iterator to the beginning of the first range.
  • last1: Iterator to the last of the first range.
  • first2: Iterator to the beginning of the second range.
  • last1: Iterator to the last of the second range.
  • result: Iterator to the beginning of the resulant data container.

This function will return the iterator to the last element of the result container where it will store the union of the two ranges.

C++ Program to Find the Union of Two Vectors

C++




// C++ program to Find the Union of two vectors
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Vectors
    vector<int> first_vector = { 10, 20, 30, 40, 50, 60 };
    vector<int> second_vector = { 10, 30, 50, 40, 60, 80 };
  
    // Sort the vector
    sort(first_vector.begin(), first_vector.end());
    sort(second_vector.begin(), second_vector.end());
  
    // Print the vector
    cout << "Vector 1: ";
    for (int i = 0; i < first_vector.size(); i++)
        cout << first_vector[i] << " ";
    cout << endl;
  
    cout << "Vector 2: ";
    for (int i = 0; i < second_vector.size(); i++)
        cout << second_vector[i] << " ";
    cout << endl;
  
    // Initialise a vector to store the common values and an
    // iterator to traverse this vector
    vector<int> v(first_vector.size()
                  + second_vector.size());
    vector<int>::iterator it, st;
  
    it = set_union(first_vector.begin(), first_vector.end(),
                   second_vector.begin(),
                   second_vector.end(), v.begin());
  
    cout << "\nUnion of two vectors:\n";
    for (st = v.begin(); st != it; ++st)
        cout << *st << ", ";
    cout << '\n';
  
    return 0;
}


Output

Vector 1: 10 20 30 40 50 60 
Vector 2: 10 30 40 50 60 80 

Union of two vectors:
10, 20, 30, 40, 50, 60, 80, 

Time Complexity: O(N*logN + MlogM), where M and N is the size of two vectors.
Space Complexity: O(N + M)



How to Find Union of Two Vectors in C++?

In C++, vectors are dynamic arrays that can grow and reduce in size as per requirements. The union of two datasets means the set of elements that consists of all the elements of the two vectors once. In this article, we will see how to find the union of two vectors in C++.

Input: 
myVector1 = {10,20,30,40,50,60}, 
myVecto2 = {10,30,50,40,60,80} 

Output:
union = {10,20,30,40,50,60,80}

Similar Reads

Finding Union of Two Vectors in C++

To find the union of two vectors in C++, we can use the std::set_union function provided by STL which can be used to find the union of two sorted ranges. So first, we have to sort both the vectors....

Contact Us