我需要创建一个哈希表,其键作为字符串,值为int。我无法在目标上使用STL容器。为此目的是否有合适的哈希表类?
答案 0 :(得分:2)
这是我刚写的一个快速的脏C哈希。编译,但在本地未经测试。不过,这个想法是让你根据需要运行它。其性能完全取决于keyToHash功能。我的版本不是高性能,但再次证明了如何做到这一点。
static const int kMaxKeyLength = 31;
static const int kMaxKeyStringLength = kMaxKeyLength + 1;
struct HashEntry
{
int value;
char key[kMaxKeyLength];
};
static const char kEmptyHash[2] = "";
static const int kHashPowerofTwo = 10;
static const int kHashSize = 1 << kHashPowerofTwo;
static const int kHashMask = kHashSize - 1;
static const int kSmallPrimeNumber = 7;
static HashEntry hashTable[kHashSize];
int keyToHash(const char key[])
{
assert(strlen(key) < kMaxKeyLength);
int hashValue = 0;
for(int i=0; < strlen(key); i++)
{
hashValue += key[i];
}
return hashValue;
}
bool hashAdd(const char key[], const int value)
{
int hashValue = keyToHash(key);
int hashFullSentinal = 0;
while(strcmp(hashTable[hashValue & kHashMask].key, kEmptyHash))
{
hashValue += kSmallPrimeNumber;
if(hashFullSentinal++ >= (kHashSize - 1))
{
return false;
}
}
strcpy(hashTable[hashValue & kHashMask].key, key);
hashTable[hashValue & kHashMask].value = value;
return true;
}
bool hashFind(const char key[], int *value)
{
int hashValue = keyToHash(key);
while(strcmp(hashTable[hashValue & kHashMask].key, kEmptyHash))
{
if(!strcmp(hashTable[hashValue & kHashMask].key, key))
{
*value = hashTable[hashValue & kHashMask].value;
return true;
}
}
return false;
}
bool hashRemove(const char key[])
{
int hashValue = keyToHash(key);
while(strcmp(hashTable[hashValue & kHashMask].key, kEmptyHash))
{
if(!strcmp(hashTable[hashValue & kHashMask].key, key))
{
hashTable[hashValue & kHashMask].value = 0;
hashTable[hashValue & kHashMask].key[0] = 0;
return true;
}
}
return false;
}
答案 1 :(得分:1)
如果您事先知道密钥列表(或其某些超集),则可以使用perfect hash function
生成器gperf
。 {{1}}将吐出C或C ++代码。
(但是,考虑到哈希函数,你可能需要做一些实际构建容器的工作。)
答案 2 :(得分:0)
你可以使用Boost的unordered associative container,又名。 boost::unordered_map
, 根据哈希表实现。
答案 3 :(得分:0)
这是一个有争议的问题,因为STL没有哈希表容器; std :: map将是另一种选择。在大多数情况下,没有理由不使用std :: map。对于需要哈希表的用法,boost :: unordered_map是最佳选择(我认为匹配新C ++ TR1提出的标准中定义的哈希表。一些编译器 - 但我不能命名它们 - 可能提供TR1哈希表作为的std :: TR1 :: unordered_map
答案 4 :(得分:0)
答案 5 :(得分:0)
如果您需要最高性能,请使用MCT's closed_hash_map
或Google's dense_hash_map
。前者更容易使用,后者更成熟。您的用例听起来好像会受到封闭散列的影响。