How to Concatenate Two Vectors in C++?
Last Updated :
15 Feb, 2024
In C++, vectors are dynamic containers that can modify their size on insertion or deletion of elements during the runtime. It stores a collection of data in the contiguous memory location. In, this article we will learn how to merge two vectors in C++.
Example:
Input:
myVector1={10, 30, 40}
myVector2 ={20, 50, 60}
Output:
myVector3 = {10,20,30,40,50,60}
Concatenate Two Vectors in C++
We can simply merge two vectors using the std::merge() function provided by the Standard Template Library (STL) of C++. The function merges two vectors into a single one in sorted order. We have to pass the iterator to the beginning and the end of the vector containers.
C++ Program to Merge Two Vectors
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > v1 = { 10, 30, 40 };
vector< int > v2 = { 20, 50, 60 };
cout << "Vector 1:" ;
for ( int num : v1) {
cout << num << " " ;
}
cout << endl;
cout << "Vector 2:" ;
for ( int num : v2) {
cout << num << " " ;
}
cout << endl;
vector< int > merged(v1.size() + v2.size());
merge(v1.begin(), v1.end(), v2.begin(), v2.end(),
merged.begin());
cout << "Merged Vector:" ;
for ( int num : merged) {
cout << num << " " ;
}
cout << endl;
return 0;
}
|
Output
Vector 1:10 30 40
Vector 2:20 50 60
Merged Vector:10 20 30 40 50 60
Time Complexity: O(N+M), where N and M are the lengths of both the vectors
Auxiliary Space: O(N+M)
Share your thoughts in the comments
Please Login to comment...