How to Delete Multiple Elements from a Vector in C++?
Last Updated :
27 Feb, 2024
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++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 1, 2, 3, 4, 5, 6, 7, 8 };
int elementsToDelete[] = { 2, 8, 7, 6 };
for ( int i = 0; i < 4; i++) {
auto it = find(myVector.begin(), myVector.end(),
elementsToDelete[i]);
if (it != myVector.end()) {
myVector.erase(it);
}
}
for ( int i : myVector) {
cout << i << " " ;
}
return 0;
}
|
Time Complexity: O(N * 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...