Open In App

How to Merge Two Sorted Vector in C++?

In C++, two sorted vectors can be merged into a single sorted vector. This can be useful when you have two lists of sorted data that you want to combine into a single list. In this article, we will learn how to merge two sorted vectors in C++.

Example:



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

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

Merge Two Sorted Vectors in C++

We can simply merge two sorted std::vectors using the std::merge() function provided by the Standard Template Library (STL) of C++. The function merges two sorted ranges into a single one in sorted order. We have to pass the iterator to the beginning and the end of the two vector containers along with the iterator to the start of the resultant vector.

Syntax of std::merge()

merge(first1, last1, first2, last2, dest );

Here,



C++ Program to Merge Two Sorted Vectors




// C++ program to illustrate how to merge two sorted vectors
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Creating two sorted vectors
    vector<int> vec1 = { 1, 3, 5 };
    vector<int> vec2 = { 2, 4, 6 };
  
    // Creating a vector to store the merged vector
    vector<int> mergedVec(vec1.size() + vec2.size());
  
    // Merging the two vectors
    merge(vec1.begin(), vec1.end(), vec2.begin(),
          vec2.end(), mergedVec.begin());
  
    // Printing the merged vector
    cout << "Merged vector: ";
    for (int i : mergedVec) {
        cout << i << " ";
    }
    cout << endl;
  
    return 0;
}

Output
Merged vector: 1 2 3 4 5 6 

Time Complexity: O(N + M), where N and M are the lengths of both the vectors respectively.
Auxiliary Space: O(N + M)

Article Tags :