Removing item from vector, while in C++11 range 'for' loop?

c++, c++11, for-loop, vector

Solution

No, you can't. Range-based `for` is for when you need to access each element of a container once.

You should use the normal `for` loop or one of its cousins if you need to modify the container as you go along, access an element more than once, or otherwise iterate in a non-linear fashion through the container.

For example:

auto i = std::begin(inv);

while (i != std::end(inv)) {
    // Do some stuff
    if (blah)
        i = inv.erase(i);
    else
        ++i;
}

Problem

I have a vector of IInventory*, and I am looping through the list using C++11 range for, to do stuff with each one. After doing some stuff with one, I may want to remove it from the list and delete the object. I know I can call `delete` on the pointer any time to clean it up, but what is the proper way to remove it from the vector, while in the range `for` loop? And if I remove it from the list will my loop be invalidated? ``` std::vector<IInventory*> inv; inv.push_back(new Foo()); inv.push_back(new Bar()); for (IInventory* index : inv) { // Do some stuff // OK, I decided I need to remove this object from 'inv'... } ```

Original source

Related problems