算法导论—哈希

来源:互联网 发布:淘宝粉丝怎么看 编辑:程序博客网 时间:2024/05/22 08:17
#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
原创粉丝点击