I'm curious about using std::string as a key in a C++ hashmap. I've heard that immutability is important for hashable types, but std::string is mutable. How does this work? Can someone explain why it's possible to use mutable types as keys in hashmaps?
5 Answers
Right! Immutable keys are usually safer since you can't change them after inserting them. But C++ gives you the freedom to use mutable keys — you just have to be responsible and not alter them once they're in the hashmap.
True! C++ doesn’t stop you from making some risky moves, like mutating keys after they've been used in a map. Your best bet is just not to mess with the strings you use as keys!
I wonder how this plays out in Python if you subclass a list to implement a __hash__ method. If you changed the list after using it as a key, would you get a weird error or just lose access to that key?
Pretty much! The hashmap needs to know it can hash the key, not whether it's mutable or not. If you create your custom types for hashmap keys, just remember to implement std::hash and overload the equality operator. It's less about mutability and more about hashing.
Although std::string is mutable, when you insert it into an unordered_map, a copy (or move) of the string is made, and only const versions are provided after that. So, changing the original string won't affect the copy stored in the map. If you mess around with it by bypassing const, you're stepping into undefined behavior territory!

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically