【发布时间】:2025-12-19 01:25:13
【问题描述】:
我正在为一个类创建一个哈希表,并且我正在尝试提高插入速度。在我的实现中,我使用了链接。向量承载字符串列表。我必须从字典中插入超过 350,000 个单词到哈希表中(我大学计算机系的 /usr/share/dict/words 中的“单词”)。
这是我的哈希表。作业可能需要任何奇怪的命名约定(例如 MyDS):
#ifndef _MYDS_H
#define _MYDS_H
#include "MyHash.h"
#include <string>
#include <vector>
#include <list>
#include <iostream>
using namespace std;
class MyDS
{
public:
MyDS()
{
max_size = 128;
size = 0;
nodes.resize(max_size);
}
// destructor
// copy constructor
// assignment operator
void push(const string& s)
{
unsigned long hash = MyHash()(s) % max_size;
list<string> & hashList = nodes[hash];
hashList.push_back(s);
if (++size > nodes.size())
{
max_size *= 4;
rehash();
}
}
bool search(const string& s)
{
unsigned long hash = MyHash()(s) % max_size;
list<string>::iterator it = nodes[hash].begin();
for (int i = 0; i < nodes[hash].size(); i++)
{
if (*it == s)
{
return true;
}
*it++;
}
return false;
}
private:
void rehash()
{
unsigned long hash;
list<string>::iterator it;
vector < list<string> > newNodes = nodes;
newNodes.resize(max_size);
for (int i = 0; i < nodes.size(); i++)
{
if (nodes[i].size() > 0)
{
it = nodes[i].begin();
hash = MyHash()(*it) % max_size;
newNodes[hash] = nodes[i];
}
}
nodes = newNodes;
}
vector< list<string> > nodes;
int max_size;
int size;
};
#endif
我使用的散列函数是 djb2。我的搜索功能和插入似乎都非常快。重新散列需要很长时间。
如果有更好的方法来设置我的哈希表,请告诉我。我在做这个项目时使用的数据结构不受限制。
【问题讨论】:
-
你复制太多了。
-
您可以将项目存储为散列(原始的、未修改的数字)和每个存储桶中的项目的对,这样就不需要重新散列了吗?只需重新读取存储的哈希值,根据新的最大大小对其进行修改并重新分配。
-
碰撞或重新散列的次数取决于散列函数。您需要在快速函数和多次重新散列或更长的执行函数和更少的冲突之间进行选择。
-
你确定每次推送都应该增加节点的一边吗?节点是每个哈希链
-
您可以/应该重写
search以减少噪音:bool search(const string & s) { auto & bucket = nodes[MyHash()(s) % max_size]; return bucket.end() != std::find(bucket.begin(), bucket.end(), s); }