It seems as if C++ does not have a hash function for strings in the standard library. Is this true?
What is a working example of using a string as a key in an unordered_map that will work with any c++ compiler?
So the bottom line is - make sure you have a #include <string> if you're trying to use strings in an unordered_map<> - actually, any time you're using std::string . Unfortunately, the compiler will sometimes let you get away without the include because of side effects from other includes.
The unordered_map::hash_function() is a built in function in C++ STL which is used to get the hash function. This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it.
Unordered_map IS a hash table actually. You may want to use a better example as, as is the second insert will fail since it has the same key.
Internally unordered_map is implemented using Hash Table, the key provided to map are hashed into indices of a hash table that is why the performance of data structure depends on hash function a lot but on an average, the cost of search, insert and delete from the hash table is O(1).
C++ STL provides template specializations of std::hash
for the various string classes. You could just specify std::string
as key type for std::unordered_map
:
#include <string> #include <unordered_map> int main() { std::unordered_map<std::string, int> map; map["string"] = 10; return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With