不使用 STL 的 C++ 哈希表

标签 c++ data-structures hashtable

我需要创建一个哈希表,其中的键是字符串,值是 int。我不能在我的目标上使用 STL 容器。是否有适合此目的的哈希表类?

最佳答案

这是我刚刚编写的一个快速的脏 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;
}

关于不使用 STL 的 C++ 哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2866878/

相关文章:

C++:二进制 std::string 到十进制

c++ - 简单的 3D OpenGL 游戏引擎

c# - 锁字典不断增长,不知如何清理?

algorithm - 为什么使用双向链表删除哈希表的元素是O(1)?

javascript - 关联数组是否像哈希表一样执行?

c++ - C++中的哈希表/无序映射

c++ - C++ (GCC) 中的四倍精度

c++ - C++中uint8_t *值的含义和调试(打印)

java - 堆数据结构再堆方法

c - 结构的动态分配和设置指针