C++ 如何实现具有2个键的哈希表?
我有一个问题:一个值,可以与两个不同的键相关联。例如:C++ 如何实现具有2个键的哈希表?,c++,key,hashtable,C++,Key,Hashtable,我有一个问题:一个值,可以与两个不同的键相关联。例如: uint64键1->值 uint32键2->值 因此,查询可以是双重的: 表.查找(uint64键1)或 表.查找(uint32键2) 键1和键2完全独立。 是否有可能实现一个表,通过两个键进行访问,而不复制项 一种可能的解决方案(psedocode): 但是,此解决方案会将表中的项目数增加一倍。我有数亿个项目,我想把整个表都保存在内存中,所以我问是否存在更高效的内存 哇,我很惊讶周围竟然没有什么想法……:-/ 因此,我实现了表,复制了
- uint64键1->值
- uint32键2->值
表.查找(uint32键2) 键1和键2完全独立。 是否有可能实现一个表,通过两个键进行访问,而不复制项 一种可能的解决方案(psedocode):
但是,此解决方案会将表中的项目数增加一倍。我有数亿个项目,我想把整个表都保存在内存中,所以我问是否存在更高效的内存 哇,我很惊讶周围竟然没有什么想法……:-/ 因此,我实现了表,复制了所有项目,如下所示:
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的内存来存储我的数据(我没有计算实际数据,“值”指向的是这些数据)
有没有办法更有效地使用内存?谢谢…欢迎来到SO!您谈论的是实现此数据结构,但没有说明您愿意使用哪种语言。同时,考虑到数亿项可能不同时都符合内存。C++。我已经实现了10多个专门的哈希表,所以我不会在低级别实现中遇到问题。仅仅是想法或算法就足够了…:-)请出示你的密码。你不可能这样得到答案。我不明白你的意思。。。我非常清楚地说明了上述课程的问题和要求。我实现的哈希表与我的问题完全无关。我只想强调,我在实现方面有相当多的经验,我在这里寻求的是算法和想法。谢谢
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_;
};