Change Object While Iterating It

Summary

In this post we will discuss how to change object while iterating it.

Details

Say we have a map.

unordered_map<char, int> char_counter ({{'1', 1}, {'a', 1}, {'b', 2}, {'c', 3}});

Now, we want to delete all elements whose value is 1. To delete an element using iterator we will use erase() function. But the problem is after erasing, this iterator “position” will become invalid. How can we get the next iterator?

The answer is it = wordMap.erase(it);.

We provide the correct version first.

for (auto && it = char_counter.begin(); it != char_counter.end();) {
        cout << (*it).first << ":" << (*it).second << endl;
        if ((*it).second == 1) {
                it = char_counter.erase(it);
        } else {
                it++;
        }
}

The following for each loop will not work.

for (const auto & k_v : char_counter) {
        if (k_v.second == 1) {
                char_counter.erase(k_v.first);
        }
}

Leave a Reply

Your email address will not be published. Required fields are marked *