-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMap.hpp
More file actions
70 lines (57 loc) · 1.57 KB
/
HashMap.hpp
File metadata and controls
70 lines (57 loc) · 1.57 KB
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
#pragma once
#include "../core/Types.hpp"
#include "Vector.hpp"
namespace Caffeine {
template<typename Key, typename Value>
class HashMap {
public:
using Pair = struct { Key key; Value value; };
HashMap() = default;
explicit HashMap(usize capacity);
Value* get(const Key& key) {
for (auto& pair : m_data) {
if (pair.key == key) return &pair.value;
}
return nullptr;
}
const Value* get(const Key& key) const {
for (const auto& pair : m_data) {
if (pair.key == key) return &pair.value;
}
return nullptr;
}
void set(const Key& key, const Value& value) {
for (auto& pair : m_data) {
if (pair.key == key) {
pair.value = value;
return;
}
}
m_data.pushBack({key, value});
}
bool contains(const Key& key) const {
for (const auto& pair : m_data) {
if (pair.key == key) return true;
}
return false;
}
void remove(const Key& key) {
for (usize i = 0; i < m_data.size(); ++i) {
if (m_data[i].key == key) {
m_data[i] = m_data.back();
m_data.popBack();
return;
}
}
}
void clear() { m_data.clear(); }
usize size() const { return m_data.size(); }
bool empty() const { return m_data.empty(); }
private:
Vector<Pair> m_data;
};
template<typename Key, typename Value>
HashMap<Key, Value>::HashMap(usize capacity) {
m_data.reserve(capacity);
}
} // namespace Caffeine