[英]Collision detection in STL's hash_map
I have to create a lookup table for C function names (as keys) to function pointers (as values). 我必须为C函数名称(作为键)到函数指针(作为值)创建查找表。 I am thinking of using STL's
hash_map
container, as the access time of a hash table is O(1)
. 我正在考虑使用STL的
hash_map
容器,因为哈希表的访问时间为O(1)
。 Is there any good hash function for this? 有什么好的哈希函数吗? Currently I am using
(31*H + c)
as my hash function. 目前,我正在使用
(31*H + c)
作为哈希函数。
Also, does STL's hash_map
takes care of collisions, or I have to take care of them in my code? 另外,STL的
hash_map
处理冲突,还是我必须在代码中处理冲突? Please give some examples if possible. 如果可能,请举一些例子。
Sample Code I am currently working upon 我目前正在使用的示例代码
#include <iostream>
#include <ext/hash_map>;
using namespace std;
using namespace __gnu_cxx;
namespace __gnu_cxx {
#ifndef __HASH_STRING__
#define __HASH_STRING__
template <>
struct hash<string> {
size_t operator() (const std::string& s) const
{
size_t h = 0;
std::string::const_iterator p, p_end;
for(p = s.begin(), p_end = s.end(); p != p_end; ++p)
{
h = 31 * h + (*p);
}
return h;
}
};
#endif
};
int main()
{
hash_map<string, int> months;
months["january"] = 1;
months["february"] = 2;
months["march"] = 3;
months["april"] = 4;
months["may"] = 5;
months["june"] = 6;
months["july"] = 7;
months["august"] = 8;
months["september"] = 9;
months["october"] = 10;
months["november"] = 11;
months["december"] = 12;
return 0;
}
You don't need to deal with collisions. 您无需处理冲突。 Also, I think std::hash is already defined, so you don't need to worry about a hash function.
另外,我认为std :: hash已经定义,因此您不必担心哈希函数。
Assuming you've got the full STL, it actually includes a hash function, hash<T>
, which in its included form is suitable for a few different key types including char* (C strings). 假设您具有完整的STL,它实际上包含一个哈希函数
hash<T>
,该哈希函数以其包含的形式适用于一些不同的键类型,包括char *(C字符串)。 I don't know details of its performance, but the STL is generally engineered to have acceptable performance for most applications. 我不了解其性能的详细信息,但STL通常被设计为对大多数应用程序具有可接受的性能。
As for collisions, that's for hash_map
to deal with, you needn't worry about it. 至于冲突,这是供
hash_map
处理的,您不必担心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.