Open In App

How to Insert an Element at a Specific Index in a Vector in C++?

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

In C++, a vector is a dynamic array that can grow and shrink in size as needed. In this article, we will learn how to insert an element at a specific position in a vector in C++.

Example:

Input:
myVector = {1, 2, 5, 4, 3, 5, 6}
insert_element: 7
index: 4

Output:
myVector = { 1, 2, 5, 4, 7, 3, 5, 6 }

Insert a Value at a Specific Position in a Vector in C++

We can insert an element at a specific position in a vector in C++ by using the std::vector::insert() function. This function takes two parameters, the iterator to the position where the new element should be inserted and the value of the new element.

C++ Program to Insert an Element at a Specific Position in a Vector

C++




// C++ program to insert an element at a specific position
// in a vector
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Initialize the vector
    vector<int> myVector = { 1, 2, 3, 4, 5 };
  
    // Position at which to insert
    int position = 3;
  
    // Element to insert
    int newElement = 6;
  
    // Insert newElement at the specified position
    myVector.insert(myVector.begin() + position,
                    newElement);
  
    // Print the vector
    for (int i = 0; i < myVector.size(); i++)
        cout << myVector[i] << " ";
  
    return 0;
}


Output

1 2 3 6 4 5 

Time Complexity: O(N), where N is the number of elements in the vector.
Space Complexity: O(1)


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

Similar Reads