【问题标题】:How to implement a hash table with 2 keys?如何实现具有 2 个键的哈希表?
【发布时间】:2013-08-21 20:45:35
【问题描述】:

我有以下问题:一个值,可以与两个不同的键相关联。示例:

  • uint64 key1 -> 值
  • uint32 key2 -> 值

所以一个查询可以是双重的:

table.find(uint64 key1) 或
table.find(uint32 key2)

key1 和 key2 是完全独立的。 是否有可能实现一个通过两个键访问而不复制项目的表?

一种可能的解决方案(psedocode):

class TwoKeyHashTable {
  Value find(uint64);
  Value find(uint32);

  insert(key1, key2, value) {
    insert_into_table(key1, value);
    insert_into_table(key2, value);
  }

  struct Item {
    uint64 key1;
    uint32 key2;
    Value value;
  } *table;
};

但是,此解决方案使表格中的项目数量增加了一倍。我有数亿个项目,我想将整个表保存在内存中,所以我想问是否存在更高效的内存?

【问题讨论】:

  • 欢迎来到 SO!您正在谈论实现此数据结构,但没有说明您愿意使用哪种或多种语言。还要考虑到数以亿计的项目可能无法一次全部放入内存中。
  • C++。我已经实现了 10 多个专门的哈希表,所以我不会遇到低级实现的问题。只是想法或算法就足够了...... :-)
  • 请出示您的密码。你不太可能通过这种方式得到答案。
  • 我不明白你的意思......我很清楚地指定了上面课程的问题和要求。我实现的哈希表与我的问题完全无关。我只想强调,我在实现方面有相当多的经验,我在这里寻求的是算法和想法。谢谢。

标签: c++ key hashtable


【解决方案1】:

哇,我很惊讶周围没有想法...... :-/ 所以我实现了表格,复制了所有项目,如下:

class TwoKeysHashTable {
 public:
  struct Item {
    uint64 key1;
    uint32 key2;
    int32 value;

    Item() : key1(0), key2(0) { }

    Item(uint64 k1, uint32 k2, int val)
       : key1(k1), key2(k2), value(val) { }
  };

  ...

  Item *Find(uint64 key) const;
  Item *Find(uint32 key) const;
  int Insert(uint64 key1, uint32 key2, int value);

 private:
  Item *FindKey1(uint64 key, int *return_index) const;
  Item *FindKey2(uint32 key, int *return_index) const;

  int GetNextIndex(int start_index, int counter) const;
  void Rehash();

  Item *array_;
  int number_key1_;
  int number_key2_;
  int allocated_items_;
};

为了不复制(真实)数据,它存储在一个压缩数组中,'Item::value' 是该数组的索引。 “Insert”调用“FindKey1”和“FindKey2”来查询表中是否已经存在键,如果没有,则将在返回的索引处插入新的项。 我使用开放散列来保持数组尽可能紧凑。尽管付出了所有努力,该表仍然为我的数据使用了超过 8GB 的​​内存(我没有计算实际数据,“值”指向)。

任何想法如何更有效地做到这一点?谢谢...

【讨论】:

    猜你喜欢
    • 2011-08-16
    • 1970-01-01
    • 2022-01-15
    • 2011-06-09
    • 2019-04-23
    • 2021-04-07
    • 2019-05-03
    • 2012-03-04
    • 2011-06-01
    相关资源
    最近更新 更多