首页 > 代码库 > C++实现hash_set

C++实现hash_set

头文件:

#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 100000
int 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 = http://www.mamicode.com/hash_fun(query);>
测试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;
}



C++实现hash_set