CSEngine
Loading...
Searching...
No Matches
SContainerHash.h
1#pragma once
2
3#include <unordered_map>
4#include <string>
5#include <algorithm>
6#include "SIContainer.h"
7
8namespace CSE {
9
10 template <class T>
11 class SContainerHash : public SIContainer<std::unordered_map<std::string, T>, T, std::string> {
12 public:
13 SContainerHash() = default;
14
15 ~SContainerHash() override = default;
16
17 void Register(T object) override {
18 std::string hash = object->GetHash();
19 if (m_objects.count(hash) > 0) {
20 throw -1;
21 return;
22 }
23 m_objects.insert(std::pair<std::string, T>(hash, object));
24 ++m_size;
25 }
26
27 void Remove(T object) override {
28 std::string hash = object->GetHash();
29 if (m_objects.count(hash) <= 0) return;
30 for (auto it = m_objects.begin(); it != m_objects.end(); ++it) {
31 if (it->second == object) {
32 m_objects.erase(it);
33 --m_size;
34 break;
35 }
36 }
37 }
38
39 bool HasHash(const std::string& hash) const {
40 return m_objects.count(hash) > 0;
41 }
42
43 T Get(std::string index) const override {
44 return m_objects.at(index);
45 }
46
47 std::unordered_map<std::string, T> GetAll() const override {
48 return m_objects;
49 }
50
51 std::string GetID(T object) const override {
52 return object->GetHash();
53 }
54
55 int GetSize() const override {
56 return m_size;
57 }
58
59 void ChangeHash(const std::string& srcHash, const std::string& dstHash) {
60 T object = m_objects.at(srcHash);
61 if(object == nullptr) return;
62 m_objects.erase(srcHash);
63 const auto& prevSize = m_objects.size();
64 m_objects.insert(std::pair<std::string, T>(dstHash, object));
65 //if(prevSize - m_objects.size() == 0) throw -1;
66 }
67
68 protected:
69 std::unordered_map<std::string, T> m_objects;
70 int m_size = 0;
71 };
72
73}