aboutsummaryrefslogtreecommitdiff
path: root/src/HashTable.cpp
blob: 685dad6e2d3c77e572da9bf865687bb19d9f599b (plain) (blame)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "HashTable.h"
#include <stdexcept>

namespace TehImage
{
	HashTable::HashTable(size_t size)
		:TABLE_SIZE(size),
		 table(TABLE_SIZE)
	{ }
	
	unsigned int HashTable::hashFunction(char key[3])
	{
		unsigned int hash = 0;
		std::memcpy(&hash, key, 3);
		return hash % TABLE_SIZE;
	}

	void HashTable::insert(char key[3], unsigned int value)
	{
		unsigned int index = hashFunction(key);
		unsigned int keyMem = 0;
		std::memcpy(&keyMem, key, 3);

		for(auto& pair : table[index])
		{
			if(pair.first == keyMem)
			{
				pair.second = value;
				return;
			}
		}

		table[index].push_back({keyMem, value});
	}

	void HashTable::remove(char key[3])
	{
		
		unsigned int index = hashFunction(key);
		unsigned int keyMem = 0;
		std::memcpy(&keyMem, key, 3);

		auto& chain = table[index];
        for (auto it = chain.begin(); it != chain.end(); ++it) {
            if (it->first == keyMem) {
                chain.erase(it);
                return;
            }
		}
	}

	unsigned int HashTable::get(char key[3])
	{
		unsigned int index = hashFunction(key);
		unsigned int keyMem = 0;
		std::memcpy(&keyMem, key, 3);

		for(auto& pair : table[index])
		{
			if(pair.first == keyMem)
			{
				return pair.second;
			}
		}

		throw std::out_of_range("Key not present");
	}

	bool HashTable::contains(char key[3])
	{
		unsigned int index = hashFunction(key);
		unsigned int keyMem = 0;
		std::memcpy(&keyMem, key, 3);

		for(auto& pair : table[index])
		{
			if(pair.first == keyMem)
			{
				return true;
			}
		}

		return false;
	}
}