[英]How to get the length of the maximum chain of a hash table?
I have a hash table program shown below我有一个哈希表程序如下所示
#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;
}
However theres specific information i need from the results that im not quite sure how to find.但是,我不太确定如何从结果中找到我需要的特定信息。 These are 2 outputs这是 2 个输出
Ive attempted to do something like this with my void Hash::loopHash()
however this function prints no values.我试图用我的void Hash::loopHash()
做这样的事情,但是这个函数不打印任何值。
If anyone knows about hash-tables and can help me with this that would be great.如果有人知道哈希表并且可以帮助我解决这个问题,那就太好了。
for(anItetator = table->begin(); anItetator != table->end(); ++anItetator){
iterates over the elements in the first std::list
, because table
is a pointer to a list<>
(but that list
is expected to the first of mod
such lists effectively forming an array of list
s). for(anItetator = table->begin(); anItetator != table->end(); ++anItetator){
迭代第一个std::list
的元素,因为table
是一个指向list<>
的指针(但是该list
预计是mod
这样的列表中的第一个,有效地形成了一个list
数组)。
What you should do to inspect each bucket in the hash table is access table
as an array, using the array length you know you called new
with to allocate the memory;检查哈希表中的每个桶应该做的是将访问table
作为一个数组,使用您知道的数组长度来调用new
来分配内存; eg例如
int num_empty_buckets = 0;
int longest_chain = 0;
for (int index = 0; index < mod; ++index) {
if (table[index].empty())
++num_empty_buckets;
longest_chain = std::max(table[index].size(), longest_chain);
}
// print 'em...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.