4
我的插入函數已經正確處理了碰撞,但是我希望能夠計算每個不同哈希方式(鏈接,線性探測和二次探測)中的碰撞次數。我將如何去做這件事?我如何計算散列表中的衝突數?
這是我到目前爲止的代碼:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <iterator>
#include <ctime>
#include "Chaining.h"
#include "QuadraticProbing.h"
#include "LinearProbing.h"
using namespace std;
int main()
{
int collision_count = 0;
float diff = 0.0;
clock_t tStart, tStop;
string ITEM_NOT_FOUND = "ITEM_NOT_FOUND";
std::vector<std::string> DataArray;
std::copy(std::istream_iterator<std::string>(std::ifstream("OHenry.txt")),istream_iterator<string>(),back_inserter(DataArray));
std::vector<std::string> QueryArray;
std::copy(std::istream_iterator<std::string>(std::ifstream("queries.txt")),istream_iterator<string>(),back_inserter(QueryArray));
cout << "Testing chaining probing...\n";
HashTable_chaining ChainingHT(ITEM_NOT_FOUND, 101);
int i = 0;
double average_c = 0.0;
double total_c = 0.0;
double temp_c = 0.0;
while(i != DataArray.size())
{
tStart = clock();
ChainingHT.insert(DataArray[i]);
tStop = clock();
total_c = tStop - tStart;
temp_c = total_c + temp_c;
average_c = total_c/DataArray.size();
if(DataArray[i] != DataArray[NULL])
{
collision_count++;
}
i++;
}
cout<<"The number of collisions using Chaining is: "<<collision_count<<endl;
cout<<"The average time per insertion using Chaining is: "<<average_c<<endl;
system("pause");
// Quadratic Probing
cout << "Testing quadratic probing...\n";
HashTable_chaining QuadraticProbingHT(ITEM_NOT_FOUND, 101);
int j = 0;
int collision_count_quadratic = 0;
double average_qp = 0;
while(j != DataArray.size())
{
clock_t tStartq = clock();
QuadraticProbingHT.insert(DataArray[j]);
if(DataArray[j] != DataArray[NULL])
{
collision_count_quadratic++;
}
j++;
average_qp = (((double)(clock() - tStartq)/CLOCKS_PER_SEC) + average_qp)/DataArray.size();
}
cout<<"The number of collisions using Quadratic is: "<<collision_count<<endl;
cout<<"The average time per insertion using Quadratic is: "<<average_qp<<endl;
非常感謝!我只是做了插入功能布爾然後使用計數器。你覺得這很好嗎? – user977154
@ user977154:它會工作得很好。但是,爲什麼要破壞插入方法的「純度」,並在循環中編寫代碼時,可以將所有這些隱藏在哈希表的方法中? – Jon
bool HashTable_qp :: insert(const string&x) { \t //插入x爲活動狀態 \t int currentPos = findPos(x); \t if(isActive(currentPos)) \t \t return false; \t array [currentPos] = HashEntry(x,ACTIVE); \t // Rehash;參見第5.5節 \t if(++ currentSize> array.size()/ 2) \t \t rehash(); \t返回true; } – user977154