Open In App

How to Insert Multiple Elements at Given Position in a Vector?

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

In C++, vectors are dynamic arrays that can increase and reduce in size as required. In this article, we will learn how to insert multiple elements at a specific position in a vector using C++.

Example:

Input: 
myVector = {10,20,30,40,50,60}
elements_to_insert = {70,80,90}
Position: 3
Output: myVector: 10 20 70 80 90 30 40 50 60

Inserting Multiple Values into a Vector at a Specific Position

To insert multiple elements at a specific position in a std::vector in C++, we can use the std::vector::insert() function that can insert the range of elements in the vector at the given position.

Syntax of std::vector::insert()

vector_name.insert(position, first, last);

 Here,

  • position: Iterator to the position where the insertion is to be done.
  • first: Iterator to the beginning of the range of elements to be inserted.
  • last: Iterator to the end of the range of elements to be inserted.

C++ Program to Insert Multiple Elements at Given Position in a Vector

The below example demonstrates how we can insert multiple elements at a specific position in a vector in C++.

C++
// C++ program to insert multiple elements at a specific
// position in a Vector

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Vector and elements to be inserted in a vector
    vector<int> vec = { 10, 20, 30, 40, 50, 60 };
    vector<int> elements_to_insert = { 70, 80, 90 };
    int position = 3;

    // Print the original vector
    cout << "Original vector: ";
    for (int i = 0; i < vec.size(); i++)
        cout << vec[i] << " ";
    cout << endl;

    // Insert elements at the 4th position in the vector
    vec.insert(vec.begin() + position - 1,
               elements_to_insert.begin(),
               elements_to_insert.end());

    // Print the vector after insertion
    cout << "Vector after insertion: ";
    for (int i = 0; i < vec.size(); i++)
        cout << vec[i] << " ";
    cout << endl;

    return 0;
}

Output
Original vector: 10 20 30 40 50 60 
Vector after insertion: 10 20 70 80 90 30 40 50 60 

Time Complexity: O(N), here N is the number of elements being inserted.
Auxilliary Space: O(M), where M is the number of elements being inserted.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads