Removing Elements from Vectors During C 11 Range-Based Loops
Range-based for loops in C 11 provide a convenient way to iterate over the elements of a container, especially when you need to perform actions on each element. However, when dealing with vectors, you may sometimes need to remove elements from the vector while iterating over it.
Problem
Consider the following code:
std::vector<IInventory*> inv; inv.push_back(new Foo()); inv.push_back(new Bar()); for (IInventory* index : inv) { // Do some stuff // ... }
Inside the loop, you realize that you need to remove a particular element from the vector inv. However, you encounter two issues:
Solution
Range-based for loops are intended for situations where you need to access each element of the container only once. If you need to modify or remove elements during iteration, you should use a traditional for loop or one of its iterator-based variations.
Here's how you can modify the code using a traditional for loop with iterator increment management:
for (auto i = inv.begin(); i != inv.end(); /*++i*/) { // Do stuff if (should_remove) { i = inv.erase(i); } else { ++i; } }
By explicitly managing the iterator increment, you maintain the validity of the loop and ensure that you can remove and modify elements without encountering any errors.
The above is the detailed content of How to Safely Remove Elements from a Vector While Iterating in C 11?. For more information, please follow other related articles on the PHP Chinese website!