How to Find Union of Two Sorted Vectors in C++?
Last Updated :
22 Feb, 2024
In C++, vectors are containers that can change their size dynamically during the runtime. The union of two vectors refers to the collection of all the distinct elements from the two original vectors. In this article, we will learn how we can find the union of two sorted vectors in C++.
Example:
Input:
myVector1 ={1,2,3,4,5}
myVector2 = {4,5,6,7,8}
Output:
Union of vectors = {1,2,3,4,5,6,7,8}
Finding Union of Two-Sorted Vectors in C++
To find the union of two sorted std::vector in C++, we can use a std::set container to store the elements of both vectors so that the repeated elements from both vectors will be stored only once and then we can copy back the elements into a resultant vector which will be the union of the given two vectors.
C++ Program to Find the Union of Two Sorted Vectors
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
vector< int > unionVectors(vector< int >& vec1,
vector< int >& vec2)
{
vector< int > ans;
set< int > s;
for ( int i = 0; i < vec1.size(); i++) {
s.insert(vec1[i]);
}
for ( int i = 0; i < vec2.size(); i++) {
s.insert(vec2[i]);
}
for ( auto it = s.begin(); it != s.end(); it++) {
ans.push_back(*it);
}
return ans;
}
int main()
{
vector< int > vec1 = { 1, 2, 3, 4, 5 };
vector< int > vec2 = { 4, 5, 6, 7, 8 };
cout << "Vector 1: " ;
for ( auto num : vec1) {
cout << num << " " ;
}
cout << endl;
cout << "Vector 2: " ;
for ( auto num : vec2) {
cout << num << " " ;
}
cout << endl;
vector< int > result = unionVectors(vec1, vec2);
cout << "Union of Vectors: " ;
for ( auto num : result) {
cout << num << " " ;
}
return 0;
}
|
Output
Vector 1: 1 2 3 4 5
Vector 2: 4 5 6 7 8
Union of Vectors: 1 2 3 4 5 6 7 8
Time complexity : O(N + M ), where N is the number of elements in vector 1 and M is number of elements in vector 2
Auxiliary Space: O(N + M)
Share your thoughts in the comments
Please Login to comment...