【发布时间】:2020-12-28 15:27:41
【问题描述】:
我有一个如下所示的哈希表程序
#include<bits/stdc++.h>
#include <algorithm>
std::string fileName;
std::fstream readFile;
const int arraySize = 100;
int storeFile[arraySize];
class Hash
{
std::list<int> *table;
std::list<int>::iterator anItetator;
public:
int count = 0;
int mod = 100;
Hash();
Hash(int Value);
void insertItem(int key);
int hashFunction(int key) {
return (key % mod);
}
void loopHash();
void displayHash();
};
Hash::Hash(){
}
Hash::Hash(int b)
{
this->mod = b;
table = new std::list<int>[mod];
}
void Hash::insertItem(int key)
{
int index = hashFunction(key);
table[index].push_back(key);
}
void Hash::displayHash() {
for (int i = 0; i < mod; i++) {
std::cout << i;
for (auto x : table[i])
std::cout << " --> " << x;
std::cout << std::endl;
}
}
void Hash::loopHash() {
for(anItetator = table->begin(); anItetator != table->end(); ++anItetator){
if(table->empty()==true) {
count++;
}
std::cout << "Total number of empty entries is: " << count;
std::cout << "The largest chain is: " << *std::max_element(table->begin(),table->end());
}
}
int main(int argc, char *argv[])
{
int n = arraySize;
Hash h(h.mod);
std::cout << "Please enter the name of the file: " << std::endl;
std::cin >> argv[0];
fileName = argv[0];
std::cout << "Attempting to read file " << fileName << std::endl;
readFile.open(fileName);
for(int i = 0; i < n; i++) {
while (readFile >> storeFile[i])
{
h.insertItem(storeFile[i]);
}
}
//h.displayHash();
h.loopHash();
readFile.close();
return 0;
}
但是,我需要从我不太确定如何找到的结果中获取特定信息。这是 2 个输出
- 哈希表中空元素的数量
- 最长链的长度
我试图用我的void Hash::loopHash() 做类似的事情,但是这个函数不打印任何值。
如果有人知道哈希表并且可以帮助我,那就太好了。
【问题讨论】:
-
与您的问题无关,但请不要将在线竞赛网站作为学习良好代码风格和良好习惯的一种方式,因为它们教的是相反的。我还建议您获得a few good books 或参加一些课程以正确学习C++,因为您的
loopHash函数包含一些非常严重的逻辑问题。更不用说您将argv[0]用作临时存储真的很糟糕。这是在哪里或谁教你的? -
我猜您需要在
if的loopHash条件中以某种方式使用anItetator?!顺便说一下,它的拼写是 iterator。 -
最近很流行使用
argv[0]来存储东西。不要这样做——这不是它的目的。写std::cin >> fileName; -
@molbdnilo:我认为这是复制和粘贴编程的症状。一个人做了一些奇怪/错误的事情,突然间你看到的越来越多。