Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Hash function for string in unordered_map

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?

like image 901
MirroredFate Avatar asked Mar 24 '13 06:03

MirroredFate


People also ask

Can we use string in unordered_map?

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.

What hash function is used in unordered_map?

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.

Is unordered_map hash table?

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.

Is unordered_map a hash map?

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).


1 Answers

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; } 
like image 154
awesoon Avatar answered Oct 25 '22 01:10

awesoon