kless135 kless135 - 17 days ago 6
C++ Question

How to iterate through a map of vectors while deleting?

I have a map of vectors in C++. For each vector, I'd like to delete entries that meet a certain condition. If a vector ends up empty, I'd like to delete it from the map. I know deletion can mess up iterators, and doubly iterating makes this even more confusing for me. What's the best way to accomplish this?

Answer

The standard mutating container loop:

for (auto it = m.begin(); it != m.end(); )
{
    // work

    if (/* need to delete */)  // e.g "if (it->second.empty())"
    {
        it = m.erase(it);
    }
    else
    {
        ++it;
    }
}
Comments