How to Remove Elements from a Vector while Iterating in C++? Last Updated : 23 Jul, 2025 Comments Improve Suggest changes Like Article Like Report 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. C++ #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; } Output1 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. Comment More info A anmolpanxq Follow Improve Article Tags : C++ Programs C++ STL cpp-vector Explore C++ BasicsIntroduction to C++ Programming Language3 min readData Types in C++7 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++5 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++11 min readFile Handling through C++ Classes8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++10 min readC++ Polymorphism5 min readEncapsulation in C++4 min readAbstraction in C++4 min readStandard Template Library(STL)Containers in C++ STL3 min readIterators in C++ STL10 min readC++ STL Algorithm Library2 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples7 min read Like