Home >Backend Development >C++ >Can You Remove Elements from a C Vector While Using a Range-Based For Loop?
Iterating and Modifying Vectors with C 11 Range Loop
When looping through a vector using C 11's range-based for, a common question arises: can you remove an item while within the loop?
Limitations of Range-based For Loops
The answer is no, as range-based for loops are designed for accessing each element of a container a single time. If you need to modify the container, remove elements, or perform non-linear iterations, you should use a traditional for loop instead.
Modifying Vectors with Traditional Loops
To remove an item from a vector while iterating, you can use a traditional for loop:
for (auto it = inv.begin(); it != inv.end(); ++it) { // Do some stuff if (blah) { it = inv.erase(it); --it; // Decrement iterator to avoid skipping an element } }
Advantages of Traditional Loops
Traditional loops offer more flexibility than range-based for loops:
The above is the detailed content of Can You Remove Elements from a C Vector While Using a Range-Based For Loop?. For more information, please follow other related articles on the PHP Chinese website!