How to Delete an Element from a Specific Position in Vector?
Last Updated :
09 Feb, 2024
In C++, the vector is a popular container that is used to store elements in the same ways as arrays but also can resize itself when needed. In this article, we’ll explore how to remove an element from a specific position in a vector using C++.
For Example,
Input:
myVector = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Delete at index 2
Output:
myVector = {1, 3, 4, 5, 6, 7, 8, 9, 10};
Erase an Element from a Specific Position in Vector
In C++, the vector containers have the std::vector::erase() member function which provides a simple way to remove the element from a specific position in a vector in C++. This function takes the position of the element in the form of an iterator as an argument.
Syntax of std::vector::erase()
myVector.erase(pos);
C++ Program to Remove an Element from a Specific Position in Vector
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 1, 2, 3, 4, 5 };
myVector.erase(myVector.begin() + 2);
cout << "Vector after deleting an element: " ;
for ( int element : myVector) {
cout << element << " " ;
}
cout << endl;
return 0;
}
|
Output
Vector after deleting an element: 1 2 4 5
Time Complexity: O(n), where m is the number of elements in the vector.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...