使用vector c ++实现哈希表

时间:2014-01-22 18:43:14

标签: c++ vector hash

我尝试使用vector实现哈希表。我的表大小将在构造函数中定义,例如,假设表大小为31,创建哈希表我执行以下操作:

vector<string> entires; // it is filled with entries that I'll put into hash table; 
vector<string> hashtable;
hashtable.resize(31);
for(int i=0;i<entries.size();i++){
    int index=hashFunction(entries[i]);
    // now I need to know whether I've already put an entry into hashtable[index] or not 
}

有没有人帮我,我怎么能这样做?

3 个答案:

答案 0 :(得分:0)

可能有多个项目用于相同的哈希值

您只需要像这样定义哈希表:

vector<vector<string>> hashtable;
hashtable.resize(32); //0-31

for(int i=0;i<entries.size();i++){
    int index=hashFunction(entries[i]);
    hashtable[index].push_back(entries[i]);
}

答案 1 :(得分:0)

哈希表的简单实现使用指向实际条目的指针向量:

    class hash_map {
    public:
    iterator find(const key_type& key);
    //...
    private:
    struct Entry {  // representation
      key_type key;
      mepped_type val;
      Entry* next;  // hash overflow link
    };

    vector<Entry> v;  // the actual entries
    vector<Entry*> b; // the hash table, pointers into v
    };

查找值运算符使用哈希函数在哈希表中查找键的索引:

mapped_type& hash_map::operator[](const key_type& k) {
  size_type i = hash(k)%b.size();  // hash
  for (Entry* p=b[i];p;p=p->next)  // search among entries hashed to i
    if (eq(k,p->key)) {  //  found
      if (p->erased) {  // re-insert
        p->erased=false;
        no_of_erased--;
        return p->val=default_value;
     }
   // not found, resize if needed
   return operator[](k);
   v.push_back(Entry(k,default_value,b[i]));  // add Entry
   b[i]=&v.back();  // point to new element

   return b[i]->val;   
}

答案 2 :(得分:0)

哈希表中的每个单元格都带有一些额外的包装。

如果您的哈希允许删除,则需要一个状态,以便可以将单元格标记为“已删除”。这使您的搜索能够继续查看,即使它遇到没有实际值的单元格。

因此,一个单元格可以有3个状态,占用,空白和删除。

您可能还希望将哈希值存储在单元格中。当您调整表格大小时,这非常有用,因为您不需要重新整理所有条目。

此外,它可以是最佳的首次比较,因为比较两个数字可能比比较两个数字更快。

如果这是一项练习,或者如果您发现std::unordered_map / std::unordered_set不适合您的目的或者您无法使用这些内容,则需要考虑这些因素。

出于实际目的,至少首先尝试使用它们。