【发布时间】:2017-04-19 06:26:09
【问题描述】:
我对旧的家庭作业有一些疑问。我希望我能得到一些帮助。我应该做的是从 .txt 文件中读取,并将该文本文件中的单词插入到链表数组中,然后散列每个单词并打印输出,以及它有多少冲突。 到目前为止,我要做的是从文本文件中读取并将其插入到链表中,但我不知道如何编写一个带有键的哈希函数来对单词进行哈希处理。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Hash {
int collisions = 0;
struct HashWords
{
string words;
struct HashWords* next;
};
HashWords* head;
public:
Hash() :collisions(0){ head = NULL; }
void Load_Dictionary();
void appendNode(string);
};
void Hash::Load_Dictionary() {
string words;
fstream in("dictionary.txt", ios::in);
while (in >> words)
{
cout << "Word: " << words << endl;
appendNode(words);
}
in.close();
}
void Hash::appendNode(string word)
{
HashWords* newNode, *nodePtr;
newNode = new HashWords;
newNode->words = word;
newNode->next = NULL;
if (!head)
head = newNode;
else
{
nodePtr = head;
while (nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
}
int main()
{
Hash dictionary;
dictionary.Load_Dictionary();
system("pause");
return 0;
}
从.txt文件中加载单词并插入到链表中,然后显示:
接下来我需要做的是创建一个键和散列函数来散列这些单词并打印结果,以及它有多少冲突。这就是我卡住的地方。
【问题讨论】:
-
您尝试过哪些与散列相关的具体方法?它既是一个广泛的话题,也是一个广泛涵盖的话题。当您在 Google 中输入“how to build a string hashmap”时,您期望得到的答案是什么?
-
您需要阅读更多关于哈希表的内容en.wikipedia.org/wiki/Hash_table。 HashTable 是最简单实现中的链表表。你只有一个链表。每个单词根据其哈希值附加到表上对应的链表中
-
我理解这个概念,这并不难。这是我无法理解的实际编码。
-
最简单的方法是使用单独的链接,例如
vector<list<Entry> > map;和void insert(Entry entry){ map[hash_function(entry)].append(entry);}。如果您使用一维结构进行存储(这是一个有效的基础),您将不会使用列表,而是使用类似数组的东西(std::vector 或 std::array),因为您需要通过索引快速访问(没有冲突,插入应该在 O(1)) 中。但是,让我们从您决定哈希函数和冲突解决方法开始。
标签: c++