How to Insert an Element at a Specific Index in a Vector in C++?
Last Updated :
27 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 1, 2, 3, 4, 5 };
int position = 3;
int newElement = 6;
myVector.insert(myVector.begin() + position,
newElement);
for ( int i = 0; i < myVector.size(); i++)
cout << myVector[i] << " " ;
return 0;
}
|
Time Complexity: O(N), where N is the number of elements in the vector.
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...