The following C++ code seems to work, and I'm curious to learn how:
std::map<char,char> mymap;
mymap['a'] = 'A'; mymap['b'] = 'B'; mymap['c'] = 'C';
mymap['d'] = 'D'; mymap['e'] = 'E'; mymap['f'] = 'F';
mymap['g'] = 'G'; mymap['h'] = 'H'; mymap['i'] = 'I';
bool erase = true;
for (auto& [key, value] : mymap) {
if (erase) mymap.erase(key); // Erasing every other item!!
erase = !erase;
}
I'm modifying the map while iterating over it. Coming from the JVM world I was expecting a CuncurrentModificationException
of sorts... but it seems to work fine in C++.
Is this actually breaking and I'm just getting lucky? If not, how does this work under the hood?
Most examples of doing this use iterators instead, I'm guessing there's a reason for that? This way look cleaner to me, I doubt someone would pick the more verbose and less legible for (auto& it = mymap::begin(); it != mymap::end; ) { it++ }
approach without a good reason for it.