How do I iterate safely under modification with std::vector in performance-sensitive code?

Iterating over a std::vector while modifying it can be risky, as it may lead to undefined behavior if not done carefully. When performance is a concern, you should consider using iterators or indexes and ensure that modifications do not interfere with the iteration process. Here are a few strategies to safely iterate while modifying a vector:

  • Use indexes: Iterate using index-based loops and access elements directly. This ensures you have control over what happens if the vector is modified.
  • Reverse iteration: If you need to remove elements, iterating in reverse can avoid issues where the removal of an element affects the positions of remaining elements.
  • Reserve space: If you're adding elements, consider using `reserve()` to reduce allocations during the loop.

Here’s an example of how to safely iterate through a vector and modify it:

std::vector vec = {1, 2, 3, 4, 5}; for (size_t i = 0; i < vec.size(); ) { if (vec[i] % 2 == 0) { vec.erase(vec.begin() + i); // Remove even numbers } else { ++i; // Only increment if we didn't remove an element } }

C++ std::vector iteration modification safe iteration performance-sensitive code C++ performance