How to Remove Elements from a Vector while Iterating in C++?
Erasing elements from a vector while iterating can be challenging because removing an element may invalidate iterators or change the size of the vector. In this article, we will learn how to erase an elements from vector while iterating in C++.
To efficiently remove elements from a vector while iterating, we use an iterator to traverse the vector. The vector erase() method removes an element and returns an iterator pointing to the next element which we assign to our current iterator. If no element is erased, we simply increment the iterator to continue the iteration.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 3, 2, 4, 5, 8};
// Erase elements while iterating
for (auto it = v.begin(); it != v.end();) {
// Remove even elements
if (*it % 2 == 0)
it = v.erase(it);
else
it++;
}
for (auto i : v)
cout << i << " ";
return 0;
}
Output
1 3 5
Explanation: In the above code, we remove all even elements from the vector. When an even element is found during iteration, we erase it using vector erase() and update the iterator with the returned value to avoid skipping any elements. If the element is not even, we simply increment the iterator to move to the next element.