forked from preshing/CompareIntegerMaps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable.h
66 lines (57 loc) · 1.55 KB
/
hashtable.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#pragma once
//----------------------------------------------
// HashTable
//
// Maps pointer-sized integers to pointer-sized integers.
// Uses open addressing with linear probing.
// In the m_cells array, key = 0 is reserved to indicate an unused cell.
// Actual value for key 0 (if any) is stored in m_zeroCell.
// The hash table automatically doubles in size when it becomes 75% full.
// The hash table never shrinks in size, even after Clear(), unless you explicitly call Compact().
//----------------------------------------------
class HashTable
{
public:
struct Cell
{
size_t key;
size_t value;
};
private:
Cell* m_cells;
size_t m_arraySize;
size_t m_population;
bool m_zeroUsed;
Cell m_zeroCell;
void Repopulate(size_t desiredSize);
public:
HashTable(size_t initialSize = 8);
~HashTable();
// Basic operations
Cell* Lookup(size_t key);
Cell* Insert(size_t key);
void Delete(Cell* cell);
void Clear();
void Compact();
void Delete(size_t key)
{
Cell* value = Lookup(key);
if (value)
Delete(value);
}
//----------------------------------------------
// Iterator
//----------------------------------------------
friend class Iterator;
class Iterator
{
private:
HashTable& m_table;
Cell* m_cur;
public:
Iterator(HashTable &table);
Cell* Next();
inline Cell* operator*() const { return m_cur; }
inline Cell* operator->() const { return m_cur; }
};
};