absence_thelab

view src/common/hashtable.h @ 0:1cffe3409164

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 23 Oct 2014 01:46:07 +0300
parents
children
line source
1 #ifndef HASHTABLE_H_
2 #define HASHTABLE_H_
4 #include <list>
5 #include <vector>
7 template <class KeyT, class ValT>
8 struct Pair {
9 KeyT key;
10 ValT val;
11 };
13 template <class KeyType, class ValType>
14 class HashTable {
15 private:
17 size_t size;
18 std::vector<std::list<Pair<KeyType, ValType> > > table;
19 //std::list<Pair<KeyType, ValType> > table[100];
21 unsigned int (*HashFunc)(const KeyType &key, unsigned long size);
22 unsigned int Hash(const KeyType &key) {return (unsigned int)HashFunc(key, (unsigned long)size);}
24 public:
26 HashTable(unsigned long size = 101);
27 ~HashTable();
29 void SetHashFunction(unsigned int (*HashFunc)(const KeyType&, unsigned long));
31 void Insert(KeyType key, ValType value);
32 void Remove(KeyType key);
34 Pair<KeyType, ValType> *Find(KeyType key);
35 };
37 //// std hash function
38 //template <class KeyType>
39 //unsigned int _HashFunction(const KeyType &key, unsigned long size) {
40 // return (size_t)key % size;
41 //}
43 // hash table member functions
44 template <class KeyType, class ValType>
45 HashTable<KeyType, ValType>::HashTable(unsigned long size) {
46 this->size = size;
47 //HashFunc = _HashFunction;
48 table.resize(size);
49 }
51 template <class KeyType, class ValType>
52 HashTable<KeyType, ValType>::~HashTable() {
53 for(unsigned long i=0; i<size; i++) {
54 table[i].erase(table[i].begin(), table[i].end());
55 }
56 }
58 template <class KeyType, class ValType>
59 void HashTable<KeyType, ValType>::SetHashFunction(unsigned int (*HashFunc)(const KeyType&, unsigned long)) {
60 this->HashFunc = HashFunc;
61 }
63 template <class KeyType, class ValType>
64 void HashTable<KeyType, ValType>::Insert(KeyType key, ValType value) {
65 Pair<KeyType, ValType> newpair;
66 newpair.key = key;
67 newpair.val = value;
69 table[Hash(key)].push_back(newpair);
70 }
72 template <class KeyType, class ValType>
73 void HashTable<KeyType, ValType>::Remove(KeyType key) {
75 unsigned int pos = Hash(key);
77 std::list<Pair<KeyType, ValType> >::iterator iter = table[pos].begin();
78 while(iter != table[pos].end()) {
79 if(iter->key == key) {
80 table[pos].erase(iter);
81 return;
82 }
83 iter++;
84 }
85 }
87 template <class KeyType, class ValType>
88 Pair<KeyType, ValType> *HashTable<KeyType, ValType>::Find(KeyType key) {
90 unsigned int pos = Hash(key);
92 std::list<Pair<KeyType, ValType> >::iterator iter = table[pos].begin();
93 while(iter != table[pos].end()) {
94 if(iter->key == key) {
95 return &(*iter);
96 }
97 iter++;
98 }
100 return 0;
101 }
103 #endif // HASHTABLE_H_