Nocturnality's blog

By Nocturnality, history, 4 months ago, In English

Inspiration

When I first started with C++, I made a common mistake: I used mp[x] > 0 to check if a key existed in a map. I didn’t realize that this method actually adds new entries to the map if the key isn’t already there. This caused confusing bugs and unexpected results in my code. From this experience, I learned how important it is to use the right methods to check for key existence. In this blog, I’ll explain why this happens and show you better ways to check if a key is in the map without changing it.

Understanding map and unordered_map

In C++, map and unordered_map are containers that store key-value pairs. The main difference is that map keeps the keys in a specific order (usually ascending), while unordered_map stores keys in no particular order, using a hash function.

The Common Mistake

Wrong Approach

While it seems like a good idea, it actually causes a problem. When you use mp[x], the map tries to find the value for x. If x isn’t in the map, it insert x in the map as key with a default value (like 0 for integers). So, checking mp[x] > 0 actually adds a new entry to the map, increasing its size.

Right Approach

Approach 1
Approach 2

Demonstrating the Impact

All in one

As shown, using mp[2] > 0 increases the map’s size, while find() and count() do not.

Conclusion

Use mp.find(x) != mp.end() or mp.count(x) == 1. These methods are safer and won’t change the map’s size. They also make debugging easier by avoiding unexpected changes to the map, helping you understand and fix issues more easily.

Happy coding!

  • Vote: I like it
  • +10
  • Vote: I do not like it

»
4 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Auto comment:

»
4 months ago, # |
  Vote: I like it +2 Vote: I do not like it

FYI, you can simply use .contains(key) since C++ 20 to not encounter this in the future. Good luck!

»
4 months ago, # |
  Vote: I like it +43 Vote: I do not like it

One thing you should be careful about when using mp.count(x): if you're using a multimap or a multiset, using count not only checks if a specific element exists, but also counts the number of that element one by one. Therefore, if there are multiple x's, it takes time proportional to the number of occurences. So if you want to check its existence only, you should use find instead.

»
4 months ago, # |
  Vote: I like it +1 Vote: I do not like it

Thank you for sharing

»
4 months ago, # |
  Vote: I like it +1 Vote: I do not like it

insightful..