我正在使用哈希表编程实验室。我们给出的代码通过重新键入密钥(通过添加一个)来处理冲突,然后再次尝试,简单,但适用于实验室。问题是,使用原始代码,如果将成员添加到完整表,它可能会进入无限循环。我们的任务是防止这种情况发生。 我使用了内容计数(contentCount),所以它不会陷入循环,即如果count> gt = = size,它就不会插入。 标题和源文件位于下方。
hashTable.h
#pragma once
#include <iostream>
using namespace std;
const int NONE = 0;
const int EMPTY = -1;
const int DELETED = -2;
class HashTable
{
public:
// Constructors
HashTable(int size);
HashTable(const HashTable & ht);
~HashTable();
// Methods
bool Insert(int key, int value);
bool Search(int key, int &value);
bool Delete(int key);
void Print();
private:
// Private methods
int Hash(int key);
int Hash2(int index);
// Private data
int Size;
int *Value;
int *Key;
int contentCount;
};
hashTable.cpp
#include "hashTable.h"
HashTable::HashTable(int size)
{
Size = size;
Value = new int[Size];
Key = new int[Size];
for (int index=0; index < Size; index++)
{
Value[index] = NONE;
Key[index] = EMPTY;
}
}
HashTable::HashTable(const HashTable & ht)
{
contentCount = 0;
Size = ht.Size;
Value = new int[Size];
Key = new int[Size];
for (int index=0; index < Size; index++)
{
Value[index] = ht.Value[index];
Key[index] = ht.Key[index];
}
}
HashTable::~HashTable()
{
delete []Value;
delete []Key;
}
bool HashTable::Insert(int key, int value)
{
if(contentCount >= Size)
{
return false;
}
// Find desired key
int index = Hash(key);
while ((Key[index] != key) && (Key[index] != EMPTY))
index = Hash2(index);
// Insert value into hash table
Value[index] = value;
Key[index] = key;
contentCount++;
return true;
}
bool HashTable::Search(int key, int &value)
{
// Find desired key
int index = Hash(key);
while ((Key[index] != key) && (Key[index] != EMPTY))
index = Hash2(index);
// Return value from hash table
if (Key[index] == key)
value = Value[index];
return (Key[index] == key);
}
bool HashTable::Delete(int key)
{
// Find desired key
int index = Hash(key);
while ((Key[index] != key) && (Key[index] != EMPTY))
index = Hash2(index);
// Delete value from hash table
if (Key[index] == key)
{
Value[index] = NONE;
Key[index] = DELETED;
contentCount--;
return true;
}
return false;
}
int HashTable::Hash(int key)
{
return key % Size;
}
int HashTable::Hash2(int index)
{
cout << "COLLISION\n";
return (index+1) % Size;
}
void HashTable::Print()
{
cout << "Index\t" << "Value\t" << "Key\n";
for (int index=0; index < Size; index++)
cout << index << "\t"
<< Value[index] << "\t"
<< Key[index] << "\n";
}
感谢您的帮助!
答案 0 :(得分:2)
您正在复制构造函数中初始化contentCount
,但在HashTable(int size)
中,您不是。
很明显,它将是未初始化的。