算法导论—哈希
来源:互联网 发布:淘宝粉丝怎么看 编辑:程序博客网 时间: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
- 算法导论—哈希
- 算法导论—堆
- 算法导论—队列
- 算法导论—红黑树
- 算法导论—KMP
- 算法导论—贪心算法
- 算法导论——第一章
- 算法导论——InversionNumbers
- 算法导论——0001
- 算法导论——栈
- 算法导论——队列
- 算法导论——哈夫曼树
- 算法导论—快速排序
- 算法导论—最小堆
- 算法导论—计数排序
- 算法导论篇—排序
- 算法导论—动态规划
- 算法导论—散列表
- 华为2015实习上机:字符串排序
- pomelo chatroom
- Git学习笔记(二)---简单的使用
- Linux程序设计(Linux shell编程的例子:获取文件列表)
- Codeforces Round #296 (Div. 2) -----A. Playing with Paper
- 算法导论—哈希
- extra qualification ‘Matrix::’ on member ‘rowTimesCol’
- 黑马程序员_学习笔记泛型
- IntelliJ idea创建spring mvc项目
- 常用的正则表达式
- 排序算法整理(一)
- 什么行业最有前途 教你如何在IT业拿高薪!
- 两种不同的方法来实现一个两列布局
- CentOS cannot change locale UTF-8解决方法及设置中文支持