算法导论—哈希

#include <iostream>
#include<vector>
#include <list>
#include <algorithm>
#include <iterator>
#include <string>
using namespace std;


template<typename HashedObj>
class hashTable
{
public:
	explicit hashTable(int size = 101)
		:currentSize(0), tableSize(size), theLists(size)
	{ }

	bool contains(const HashedObj& x)
	{
		const list<HashedObj> &whichList = theLists[myhash(x)];
		return find(whichList.begin(), whichList.end(), x) != whichList.end();
	}

	void makeEmpty()
	{
		for (auto list : theLists)
			list.clear();
		currentSize = 0;
	}

	/**
	 * insert x to the hashtable,if x had existed ,do nothing
	 */
	bool insert(const HashedObj &x)
	{
		if (!theLists[myhash(x)].empty())
			collision++;
		list<HashedObj> &whichList = theLists[myhash(x)];
		if (find(whichList.begin(), whichList.end(), x) != whichList.end())
			return false;
		whichList.push_back(x);

		return true;
	}

	/**
	 * remove x from hashtable, if x not exist,return false
	 */
	bool remove(const HashedObj &x)
	{
		list<HashedObj> &whichList = theLists[myhash(x)];
		list<HashedObj>::iterator itr = find(whichList.begin(), whichList.end(), x);

		if (itr == whichList.end())
			return false;

		whichList.erase(itr);
		--currentSize;
		return true;
	}

	void print()
	{
		for (auto list : theLists)
			for (auto s : list)
				cout << s << endl;
	}

	int collisionSize()
	{
		return collision;
	}

	int capacity()
	{
		return theLists.capacity();
	}

private:
	vector<list<HashedObj>> theLists;  
	int tableSize;
	int currentSize;
	int collision = 0;

	int myhash(const HashedObj &x)
	{
		int hashVal = 0;

		for (auto c : x)
			hashVal = 37 * hashVal + c;

		hashVal = hashVal%tableSize;
		if (hashVal < 0)
			hashVal += tableSize;
		return hashVal;
	}

};
#include "tree.h"
#include "hash.h"
#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;


string rand_str(int len)
{
	string s;
	int i;
	for (i = 0; i < len; ++i)
		s.push_back('A' + rand() % 26);
	return s;
}

int main()
{
	/*
	BinarySearchTree<int> tree;
	tree.insert(5);
	tree.insert(15);
	tree.insert(1);
	tree.printTree();
	**/

	int i=0;
	hashTable<string> hs;
	cout << hs.capacity() << endl;

	while (i <50)
	{
		hs.insert(rand_str(10));
		i++;
	}
	hs.print();
	cout << hs.collisionSize() << endl;
	system("pause");
	
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值