Open In App

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

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

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,

  • first_vector.end(): Iterator to the end of the first vector where new elements are inserted.
  • second_vector.begin(): Iterator to the beginning of the second vector.
  • second_vector.end(): Iterator to the end of the second vector.

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




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads