Can I Use std::string as a Key in a C++ Hashmap Even Though It’s Mutable?

0
12
Asked By CuriousCoder92 On

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

Answered By DevDude41 On

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.

Answered By StringSmith99 On

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!

Answered By SyntaxSavant On

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?

Answered By MapMaster23 On

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.

Answered By CodeWiz74 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.