Open In App

How to Merge Two Sorted Vector in C++?

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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,

  • first1: Iterator to the start of the first vector.
  • last1: Iterator to the end of the first vector.
  • first2: Iterator to the start of the second vector.
  • last2: Iterator to the end of the second vector.
  • dest: Iterator to the start of the resultant vector.

C++ Program to Merge Two Sorted Vectors

C++




// 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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads