Skip to content
Related Articles

Related Articles

How to join two Arrays using STL in C++?

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 07 Jul, 2022
View Discussion
Improve Article
Save Article

Given two arrays, join these two arrays using STL in C++. Example:

Input: arr1[] = {1, 45, 54, 71, 76, 12}, arr2[] = {1, 7, 5, 4, 6, 12} Output: {1, 4, 5, 6, 7, 12, 45, 54, 71, 76} Input: arr1[] = {1, 7, 5, 4, 6, 12}, arr2[] = {10, 12, 11} Output: {1, 4, 5, 6, 7, 10, 11, 12}

Approach: Joining can be done with the help of set_union() function provided in STL. Syntax:

set_union (InputIterator1 first1, InputIterator1 last1,
           InputIterator2 first2, InputIterator2 last2,
           OutputIterator result);

Below is the implementation of the above approach: 

CPP




// C++ program to join two Arrays
// using set_union() in STL
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
  // Get the array
  int arr1[] = { 1, 45, 54, 71, 76, 12 };
  int arr2[] = { 1, 7, 5, 4, 6, 12 };
 
  // Compute the sizes
  int n1 = sizeof(arr1) / sizeof(arr1[0]);
  int n2 = sizeof(arr2) / sizeof(arr2[0]);
 
  // Sort the arrays
  sort(arr1, arr1 + n1);
  sort(arr2, arr2 + n2);
 
  // Print the array
  cout << "First Array: ";
  for (int i = 0; i < n1; i++)
    cout << arr1[i] << " ";
  cout << endl;
 
  cout << "Second Array: ";
  for (int i = 0; i < n2; i++)
    cout << arr2[i] << " ";
  cout << endl;
 
  // Initialise a vector
  // to store the merged values
  // and an iterator
  // to traverse this vector
  vector<int> v(n1 + n2);
  vector<int>::iterator it, st;
 
  it = set_union(arr1, arr1 + n1,
        arr2, arr2 + n2,
        v.begin());
 
  // Print the merged array
  cout << "\nAfter joining:\n";
  for (st = v.begin(); st != it; ++st)
    cout << *st << ", ";
  cout << '\n';
 
  return 0;
}


Output:

First Array: 1 12 45 54 71 76 
Second Array: 1 4 5 6 7 12 

After joining:
1, 4, 5, 6, 7, 12, 45, 54, 71, 76,

Time Complexity: O(nlogn)
Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!