Open In App

How to Remove an Element from Vector in C++?

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

In C++, vectors are the same as arrays but they can resize themselves automatically when required as their storage is handled automatically by the container. In this article, we will learn how to remove a specific element from a vector in C++

Example:

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

Output:
// removed element 5 from the vector
myVector = {1, 2, 3, 4, 6, 7, 8}

Erase a Specific Element from a Vector in C++

In C++, the std::vector class template provides a member function std::vector::erase() which can be used to remove a specific element from a vector. The erase function accepts the position of the element to be removed and then removes that element from the vector. We can find the position of the specific element we want to remove using the std::find method.

C++ Program to Erase a Specific Element from a Vector

C++




// C++ program to remove a specific element from the vector
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // initialize the vector
    vector<int> myVector = { 1, 2, 3, 4, 5, 6, 7, 8 };
  
    // Print the vector before deletion
    cout << "Vector Before Deletion:";
    for (int element : myVector) {
        cout << element << " ";
    }
    cout << endl;
  
    int elementToRemove = 5;
  
    // Remove the element using erase function and iterators
    auto it = std::find(myVector.begin(), myVector.end(),
                        elementToRemove);
  
    // If element is found found, erase it
    if (it != myVector.end()) {
        myVector.erase(it);
    }
  
    // Print the vector after deletion
    cout << "Vector After Deletion:";
    for (int element : myVector) {
        cout << element << " ";
    }
    cout << endl;
  
    return 0;
}


Output

Vector Before Deletion:1 2 3 4 5 6 7 8 
Vector After Deletion:1 2 3 4 6 7 8 

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads