How to Merge Two Sorted Vector in C++?
Last Updated :
23 Jul, 2025
Merging two sorted vectors means storing the elements of a vector into a single vector in a sorted order. In this article, we will learn how to merge two sorted vectors in C++.
The simplest way to merge the two sorted vectors is by using the merge() function. Let’s take a look at an example:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v1 = {1, 3, 5};
vector<int> v2 = {2, 4, 6};
// Creating a vector to store merged vector
vector<int> v(v1.size() + v2.size());
// Merging the two vectors
merge(v1.begin(), v1.end(), v2.begin(),
v2.end(), v.begin());
for (auto i : v)
cout << i << " ";
return 0;
}
Explanation: The merge() function merge the two vectors v1 and v2 in sorted manner and store it in the resultant vector v.
There are also some other methods in C++ to merge the two sorted vector. Some of them are as follows:
By Sorting After Concatenation
Copy both the vectors into resultant vector using vector insert() method. After that, sort the resultant using sort() to arrange the elements in sorted order.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v1 = {1, 3, 5};
vector<int> v2 = {2, 4, 6};
// Creating a vector to store the merged vector
vector<int> v;
// Insert v1 and v2 into vector v
v.insert(v.end(), v1.begin(), v1.end());
v.insert(v.end(), v2.begin(), v2.end());
// Sort the vector v
sort(v.begin(), v.end());
for (auto i : v)
cout << i << " ";
return 0;
}
Using Multiset
A multiset stores its elements in a sorted order by default. It can be used as a temporary storage medium to combine the elements of both vectors while maintaining sorted order, and then transfer all the elements into the resultant vector.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v1 = {1, 3, 5};
vector<int> v2 = {2, 4, 6};
// Insert elements of v1 and v2 into multiset
multiset<int> ms(v1.begin(), v1.end());
ms.insert(v2.begin(), v2.end());
// Copying elements of multiset into vector v
vector<int> v(ms.begin(), ms.end());
for (auto i : v)
cout << i << " ";
return 0;
}
Explore
C++ Basics
Core Concepts
OOP in C++
Standard Template Library(STL)
Practice & Problems