You should've asked this on stackoverflow instead of codereview. But the answer is "yes" it is UB. To fix it just rewrite the part as: if(it->second==0) { it = _m.erase(it); } else { it++; }