Home >Backend Development >C++ >Can We Remove Elements from a Vector Inside a C 11 Range-Based For Loop?
Removing Elements from Vectors in C 11 Range-Based Loops
In C 11, range-based for loops offer a convenient way to iterate through container elements. However, removing elements from the container within these loops poses a challenge.
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 // I need to remove this object from 'inv'... }
Can We Remove Elements Within Range-Based Loops?
No, you cannot remove elements from a vector within a range-based for loop. This is because the loop operates by creating a copy of the vector iterator, which becomes invalidated if elements are removed or added.
Therefore, it is crucial to consider alternative approaches for modifying containers during iteration.
Recommended Solution
The recommended approach is to use the traditional for loop or one of its variants. This allows you to directly manipulate the vector and remove elements as needed. For example:
auto i = std::begin(inv); while (i != std::end(inv)) { // Do some stuff if (blah) i = inv.erase(i); else ++i; }
The above is the detailed content of Can We Remove Elements from a Vector Inside a C 11 Range-Based For Loop?. For more information, please follow other related articles on the PHP Chinese website!