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:
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
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?