How to remove multiple items from unordered map while iterating over it?

Niko picture Niko · Mar 27, 2013 · Viewed 17.1k times · Source

Please consider the following situation:

using namespace std;
unordered_map<int, vector<A>> elements;

Now I'm iterating over this unordered map:

for (auto it = elements.begin(); it != elements.end(); ++it)

Inside the loop, I'm forming clusters out of several elements of elements (the current one that it points to and some more, not necessarily those next in line!). Because each element can be only part of one cluster, I'd like to remove those from the map and then continue with the next element (i.e., build the next cluster).

How can I do this and still continue the iteration at the correct position?

Answer

user995502 picture user995502 · Mar 27, 2013
for (auto it = elements.begin(); it != elements.end();) {
   if(you have to rease) {
      it = elements.erase(it);
   }
   else
      it++;
}

This way you make sure you don't increment after erasing and alos you don't increment the end().

After suggestions that there's no good reason to have for loop that doesn't increment anything you might want to us a while loop instead. Mainly for more readability.