Open In App

How to Append a Vector to a Vector in C++?

In C++, vectors are dynamic arrays that can grow and reduce in size as per requirements and sometimes, we need to append one vector to another. In this article, we will learn how to append a vector to another vector in C++.

Example:

Input:
first_vector = {10, 20, 30, 40, 50, 60};
second_vector = {70, 80, 90, 100};

Output:
Appended Vector: {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}

Append a Vector to a Vector in C++

To append a std::vector to another vector in C++, we can use std::vector::insert() function provided in the std::vector class template that can insert new elements from the given range at the specified position.

Syntax of vector::insert()

first_vector.insert(first_vector.end(), second_vector.begin(), second_vector.end());

Here,

C++ Program to Append a Vector to Another Vector

The below program demonstrates how we can use std::insert() function to append elements of one vector to another vector in C++ STL.

// C++ program to illustrate how to append a vector to
// another vector
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Creating Vectors
    vector<int> first_vector = { 10, 20, 30, 40, 50, 60 };
    vector<int> second_vector = { 70, 80, 90, 100 };

    // Append the second vector to the first vector
    first_vector.insert(first_vector.end(),
                        second_vector.begin(),
                        second_vector.end());

    cout << "Appended Vector: ";
    for (int i = 0; i < first_vector.size(); i++)
        cout << first_vector[i] << " ";
    cout << endl;

    return 0;
}

Output
Appended Vector: 10 20 30 40 50 60 70 80 90 100 

Time Complexity: O(N), here N is the size of the second vector.
Auxiliary Space: O(1)



Article Tags :