hash_map questions / tutorial
I know how hashmap works in Java. But I can't fully understand in C++.
I found some simple tutorials, but there are no hashfunctions etc..
Does a string need hash function?
hash_map<string, string> hm;
hm.insert(make_pair("one", "two"));
hm.insert(make_pair("t开发者_如何学运维hree", "four"));
how will it work without hash functions for string? how to add hash func?
Is there any good tutorial for hash_map?
Thank you!
For starters, hash_map
is not a standard C++ library; it's a compiler extension that ships with Visual Studio and g++. If you want to use a more standardized hash table in C++, look at either the Boost.Unordered libraries, the TR1 hash containers, or, if you have a more modern compiler, the new C++0x standard hash container types. These containers, which are named unordered_map
and unordered_set
rather than the more suggestive hash_map
or hash_set
, have more standardized support and are more portable.
As to your question about how to specify a hash function, the hash_map
has built-in hash functions for most of the standard types, including std::string
, and so you don't need to specify one. If you do want to define your own hash function, you should create a function object that overloads operator()
to provide a hash code, then parameterize the hash_map
over that type in addition to the other types. For example:
struct MyCustomHash {
size_t operator() (const string& str) const {
/* Terrible hash function... for instructional purposes only! */
return str.empty()? 0 : str[0];
}
};
hash_map<string, int, MyCustomHash> myHashMap;
Now myHashMap
will use MyCustomHash
instead of the default hash function.
Hope this helps!
Which hashmap implementation are you using? The one added in C++0x, std::unordered_map, already define hash functions for some types (including strings). If you try to use a hashmap without a hash function it won't compile (the error will occur when you try to insert something).
精彩评论