Search code examples
c++loopseraseerase-remove-idiom

Erase in a loop with a condition in C++


Is there a better way to write:

for (auto i = container.begin(); i != container.end();)
{
    if (condition(i))
    {
       i = container.erase(i);
       continue;
    }
    ++i;
}

This code does what I want, but it feels like bad style.

How can I improve it?

My container is std::map, but a generic solution would be cool.


Solution

  • Use erase + remove_if:

    auto pred = /* lambda or something*/
    container.erase(std::remove_if(container.begin(),
                                   container.end(),
                                   pred)