Open In App

How to Add Multiple Elements at the End of Vector in C++?

Last Updated : 01 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. In this article, we will learn how to add multiple elements at the end of a vector in C++.

Example

Input:
myVector = {10, 20, 30, 40, 50}
elements_to_add = {60, 70, 80}

Output:
updated_vector: 10 20 30 40 50 60 70 80

Insert Multiple Elements at the End of Vector in C++

To add multiple elements at the end of a std::vector in C++, we can use the std::vector::insert() function provided that inserts the range containing new elements before the element at the specified position.

Syntax of std::vector::insert()

vectorName.insert(position, start, end);

Here,

  • position: Iterator pointing to the position which the new elements will be inserted before.
  • start: Iterator pointing to the beginning of the range to be copied.
  • end: Iterator pointing to the end of the range to be copied.

C++ Program to Add Multiple Elements at the End of a Vector

The below example demonstrates how we can add multiple elements at the end of a vector in C++ STL.

C++




// C++ program to illustrate how to add multiple elements at
// the end of a vector
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Vector
    vector<int> myVector = { 10, 20, 30, 40, 50 };
  
    // Elements to add
    vector<int> elements_to_add = { 60, 70, 80 };
  
    // Print the original vector
    cout << "Original Vector: ";
    for (int i = 0; i < myVector.size(); i++)
        cout << myVector[i] << " ";
    cout << endl;
  
    // Add elements at the end of the vector
    myVector.insert(myVector.end(), elements_to_add.begin(),
                    elements_to_add.end());
  
    // Print the updated vector
    cout << "Updated Vector: ";
    for (int i = 0; i < myVector.size(); i++)
        cout << myVector[i] << " ";
    cout << endl;
  
    return 0;
}


Output

Original Vector: 10 20 30 40 50 
Updated Vector: 10 20 30 40 50 60 70 80 

Time Complexity: O(M), where M is the number of elements to be added.
Auxiliary Space: O(M)



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

Similar Reads