【问题标题】:implementing hash table using vector c++使用vector c++实现哈希表
【发布时间】:2014-02-13 00:05:21
【问题描述】:

我尝试使用向量实现哈希表。我的表大小将在构造函数中定义,例如表大小为 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 
}

有没有人可以帮助我,我该怎么做?

【问题讨论】:

  • 这是你的真实代码吗?我可以发现至少 2 个错误(缺少右括号和您拼写错误的条目)
  • @Borgleader 不,我只是为了简化而写了其中的一部分。抱歉打错了
  • @TheGost 检查hashtable[index].empty()?不过,我不明白您打算如何使用向量实现哈希表。对于哈希到同一索引的 2 个不同条目,您将如何处理?
  • 线性或二次探测?我没有显示那部分代码,请帮我问@Praetorian
  • 呃,我评论的第一句话不就是这样吗?

标签: c++ vector hash


【解决方案1】:

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

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

所以一个单元格可以有 3 种状态,占用、空和删除。

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

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

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

出于实际目的,至少先尝试使用这些。

【讨论】:

    【解决方案2】:

    同一个哈希值可以有多个项目

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

    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]);
    }
    

    【讨论】:

    • 不,如果有条目,我将使用线性探测冲突解决策略,因此同一位置不能有多个条目
    • 所以看起来你需要使用默认值作为空值(如果空字符串不适合这个)
    【解决方案3】:

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

        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;   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-30
      • 2012-05-27
      • 2017-03-20
      • 2012-10-30
      • 2020-12-30
      • 1970-01-01
      • 2016-03-25
      相关资源
      最近更新 更多