C++实现hash_set

来源:互联网 发布:程序编程和软件开发 编辑:程序博客网 时间:2024/05/16 18:52

头文件:

#include<iostream>using namespace std;template<class hash_type>class hash_set{private:hash_type array[100000];int hash_fun(hash_type original);public:hash_set();//构造函数void insert(hash_type value);//插入一个元素void erase(hash_type target);//删除一个元素bool contain(hash_type query);//判断一个元素是否在集合中};
类函数实现:

#include "hash_set.h"template<class hash_type>#define MAX_LENGTH 100000int hash_set<hash_type>::hash_fun(hash_type original){return ((int)original) % MAX_LENGTH;}template<class hash_type>hash_set<hash_type>::hash_set(){ for(int i = 0; i < MAX_LENGTH; i++) array[i] = NULL;}template<class hash_type>bool hash_set<hash_type>::contain(hash_type query){int hash_value = hash_fun(query);while(array[hash_value] != NULL){if(array[hash_value] == query)return true;hash_value++;if(hash_value >= MAX_LENGTH)hash_value = 0;}return false;}template<class hash_type>void hash_set<hash_type>::insert(hash_type value){if(contain(value)){cout << "The value exists.\n";return;}int hash_value = hash_fun(value);while(array[hash_value] != NULL){hash_value++;if(hash_value >= MAX_LENGTH)hash_value = 0;}array[hash_value] = value;}template<class hash_type>void hash_set<hash_type>::erase(hash_type target){int hash_value = hash_fun(target);while(array[hash_value] != NULL){if(array[hash_value] == target)break;hash_value++;if(hash_value >= MAX_LENGTH)hash_value = 0;}if(array[hash_value] == NULL)cout << "The value doesn't exist.\n";elsearray[hash_value] = NULL;}

测试main函数:

#include<iostream>#include "hash_set.cpp"int main(){hash_set<int> hs;while(true){cout << "Begin test:\ninput 1 to insert;2 to find; 3 to delete\n";int flag;int value;cin >> flag;switch (flag){case 1:cout << "input the value to insert:\n";cin >> value;hs.insert(value);break;case 2:cout << "input the value to find:\n";cin >> value;if(hs.contain(value))cout << "Yes\n";else cout << "No\n";break;case 3:cout << "input the value to delete\n";cin >> value;hs.erase(value);break;default:cout << "Input error.\n";break;}}return 0;}



0 0