Open In App

How to Delete Multiple Elements from a Vector in C++?

In C++, vectors are data structures similar to arrays that allow the users to store data in contiguous memory locations, but unlike arrays, vectors are dynamic in nature. In this article, we will learn how to delete multiple elements from a vector in C++.

Example:



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

Output:
myVector ={2, 4, 6, 8}

Erase Multiple Elements from a Vector in C++

To delete multiple elements from a vector in C++, we can use the std::find() method along with a loop to identify the elements we want to remove and then use the vector::erase() method to remove those elements from the vector.

C++ Program to Erase Multiple Elements from a Vector




// C++ Program to Delete Multiple Elements from a Vector
#include <algorithm>
#include <iostream>
#include <vector>
  
// Use the standard namespace
using namespace std;
  
int main()
{
    // Initialize the vector with the given elements
    vector<int> myVector = { 1, 2, 3, 4, 5, 6, 7, 8 };
  
    // Elements to be deleted
    int elementsToDelete[] = { 2, 8, 7, 6 };
  
    // Loop through each element to delete
    for (int i = 0; i < 4; i++) {
        // Find the element in the vector
        auto it = find(myVector.begin(), myVector.end(),
                       elementsToDelete[i]);
  
        // If the element is found, erase it
        if (it != myVector.end()) {
            myVector.erase(it);
        }
    }
  
    // Print the elements of the vector after deletion
    for (int i : myVector) {
        cout << i << " ";
    }
  
    return 0;
}

Output

1 3 4 5 

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


Article Tags :