Open In App

How to Delete an Element from a Specific Position in Vector?

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

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++




// C++ Program to demonstrate deleting an element from a
// specific position in a vector
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initializing a vector with some elements
    vector<int> myVector = { 1, 2, 3, 4, 5 };
  
    // Deleting an element from a specific position (index
    // 2) using erase()
    myVector.erase(myVector.begin() + 2);
  
    // Printing the vector after deleting the element
    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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads