Open In App

How to Concatenate Two Vectors in C++?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to illustrate how to merge two vectors into a
// single one
#include <algorithm>
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Define the input vectors
  
    vector<int> v1 = { 10, 30, 40 };
    vector<int> v2 = { 20, 50, 60 };
  
    // Print the original vectors
    cout << "Vector 1:";
    for (int num : v1) {
        cout << num << " ";
    }
    cout << endl;
  
    cout << "Vector 2:";
    for (int num : v2) {
        cout << num << " ";
    }
    cout << endl;
  
    // intialize a vector to accomodate elememnts from both
    // vectors
  
    vector<int> merged(v1.size() + v2.size());
  
    // Merge the vectors using the merge function
  
    merge(v1.begin(), v1.end(), v2.begin(), v2.end(),
          merged.begin());
  
    // Print the merged vector
    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)



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

Similar Reads