码迷,mamicode.com
首页 > 编程语言 > 详细

C++实现hash_set

时间:2014-10-08 00:36:14      阅读:349      评论:0      收藏:0      [点我收藏+]

标签:算法   c++   

头文件:

#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 = 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";
	else
		array[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;
}



C++实现hash_set

标签:算法   c++   

原文地址:http://blog.csdn.net/u012999424/article/details/39859321

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!