【发布时间】:2017-04-04 06:48:03
【问题描述】:
我正在用 C++ 编写自己的 HashTable 类,需要向用户输出表中每个字符串的出现次数。例如,如果这是输入:testing, 1, 2, testing,这是哈希表(通过链接和节点指针完成):
[0]->testing, testing
[1]->2
[2]->1
这将是用户的输出(计数,后跟单词):
2 testing
1 2
1 1
我遇到的问题是如何跟踪哈希表中每个单词的数量,或者如何找到它。我从this question 开始,但无法在我的代码中实现另一个数组。
我也尝试了this question 中的解决方案,但由于我使用了指针/链式哈希,它不起作用。
我的问题是,我是否需要使用单独的字符串数组来跟踪已使用的内容,或者是否有一种简单的方法可以递归地遍历哈希表的每个索引并打印出出现的次数每个字符串?我想我需要在 insert 函数或 printData 函数中完成此操作。
供参考,这是我的代码:
HashTable.h:
#include <string>
#include <iostream>
using namespace std;
struct Entry {
string word;
Entry* next;
};
class HashTable {
public:
HashTable();
HashTable(int);
int hash(string);
void insert(string);
void printData();
int getCapacity() const;
private:
//Member variables
int CAPACITY; // The initial capacity of the HashTable
Entry **data; // The array to store the data of strings (Entries)
};
HashTable.cpp:
#include "HashTable.h"
HashTable::HashTable()
{
CAPACITY = 0;
data = new Entry*[0];
}
HashTable::HashTable(int _cap)
{
CAPACITY = _cap;
data = new Entry*[_cap];
for (int i = 0; i < CAPACITY; i++) {
data[i] = new Entry;
data[i]->word = "empty";
data[i]->next = nullptr;
}
}
int HashTable::hash(string key)
{
int hash = 0;
for (unsigned int i = 0; i < key.length(); i++) {
hash = hash + (int)key[i];
}
return hash % CAPACITY;
}
void HashTable::insert(string entry)
{
int index = hash(entry);
if (data[index]->word == "empty") {
data[index]->word = entry;
} else {
Entry* temp = data[index];
Entry* e = new Entry;
e->word = entry;
e->next = nullptr;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = e;
}
}
void HashTable::printData()
{
for (int i = 0; i < CAPACITY; i++) {
if (data[i]->next != nullptr) {
while(data[i]->next != nullptr) {
cout << data[i]->word << " -> ";
data[i] = data[i]->next;
}
cout << data[i]->word << endl;
} else {
cout << data[i]->word << endl;
}
}
}
int HashTable::getCapacity() const
{
return CAPACITY;
}
注意:我不能使用标准 C++ 库中的任何函数/数据结构。
【问题讨论】: