Doubt in map container in c++

map<char,int> m
for(auto itr:m) {
m[itr->first]–;
if(m[itr->first]==0)
m.erase(itr->first);
}

the map contains {<‘a’,3> ans <‘b’,1>} as element.
when i run this program the loop runs 3 times but when i dont erase elemt from map it runs 2 time can anyone explain me this behaviour?

1 Like

actually it is itr.first instead of itr->first

and m[itr->first]–-;

When you use auto : it.first or it.second
When you use iterator : it->first and it->second

1 Like

You are modifying the map while iterating the container. The interators get invalidated, and its undefined behaviour.

1 Like