Fix cppcheck reports (part2):

- (error) Iterator 'oni' used after element has been erased
- (error) Dangerous iterator comparison using operator< on 'std::map'
- (style) Unused variable: it
- (error) Memory pointed to by 'counts' is freed twice
- (error) Memory pointed to by 'key' is freed twice