How do I erase elements while iterating with std::vector in performance-sensitive code?

In C++, erasing elements from a `std::vector` while iterating can lead to issues like invalidating iterators, which may result in undefined behavior. To manage this safely and efficiently, you can use techniques such as the `erase-remove` idiom, or use reverse iteration. Below, we provide a code example illustrating how to safely erase elements from a vector during iteration.

#include #include #include int main() { std::vector myVector = {1, 2, 3, 4, 5, 6}; // Using erase-remove idiom myVector.erase(std::remove_if(myVector.begin(), myVector.end(), [](int value) { return value % 2 == 0; }), myVector.end()); for (int value : myVector) { std::cout << value << " "; // Output: 1 3 5 } std::cout << std::endl; // Alternative: Reverse iteration for (auto it = myVector.rbegin(); it != myVector.rend(); ) { if (*it % 2 == 0) { it = std::vector::reverse_iterator(myVector.erase((it + 1).base())); } else { ++it; } } for (int value : myVector) { std::cout << value << " "; // Output: 1 3 5 } return 0; }

C++ std::vector erase iterating performance-sensitive code erase-remove idiom reverse iteration