📄 hashcontainer.h
字号:
#pragma once
#include "Config.h"
template<class T> class HashContainer
{
bool deleteObjAlso;
T** arr;
TCHAR** arrid;
int arrCount;
int arrSize;
void clear();
void init();
void enlargeArrIfNeed();
public:
HashContainer(bool deleteObjAlso);
HashContainer();
~HashContainer();
int GetCount() { return this->arrCount; }
void Clear();
int GetIndex(const TCHAR* id);
TCHAR* GetKey(int index);
int Add(const TCHAR* id, T* obj);
T*& operator [] (const TCHAR* id);
T*& operator [] (int index);
};
template<class T> HashContainer<T>::HashContainer()
{
this->deleteObjAlso = true;
this->init();
}
template<class T> HashContainer<T>::HashContainer(bool deleteObjAlso)
{
this->deleteObjAlso = deleteObjAlso;
this->init();
}
template<class T> HashContainer<T>::~HashContainer()
{
this->clear();
}
template<class T> void HashContainer<T>::init()
{
this->arrCount = 0;
this->arrSize = 2;
this->arr = new T*[this->arrSize];
this->arrid = new TCHAR*[this->arrSize];
}
template<class T> void HashContainer<T>::clear()
{
for (int i=0; i<this->arrCount; i++)
delete[] this->arrid[i];
delete[] this->arrid;
this->arrid = 0;
if (this->deleteObjAlso)
{
for (int i=0; i<this->arrCount; i++)
delete this->arr[i];
}
delete[] this->arr;
this->arr = 0;
this->arrCount = 0;
this->arrSize = 0;
}
template<class T> void HashContainer<T>::Clear()
{
clear();
init();
}
template<class T> void HashContainer<T>::enlargeArrIfNeed()
{
if (this->arrCount == this->arrSize)
{
int newSize = this->arrSize*2;
T** newarr = new T*[newSize];
TCHAR** newarrid = new TCHAR*[newSize];
CopyMemory(newarr, this->arr, sizeof(T*)*this->arrSize);
CopyMemory(newarrid, this->arrid, sizeof(TCHAR*)*this->arrSize);
delete[] this->arr;
delete[] this->arrid;
this->arr = newarr;
this->arrid = newarrid;
this->arrSize = newSize;
}
}
template<class T> int HashContainer<T>::GetIndex(const TCHAR* id)
{
for (int i=0; i<this->arrCount; i++)
{
if (0 == wcscmp(this->arrid[i], id)) return i;
}
return -1;
}
template<class T> TCHAR* HashContainer<T>::GetKey(int index)
{
if (index < 0 || index >= this->arrCount) throw L"HashContainer: Index Out Of Bounds";
return (this->arrid[index]);
}
template<class T> int HashContainer<T>::Add(const TCHAR* id, T* obj)
{
this->enlargeArrIfNeed();
int index = this->arrCount;
this->arrCount++;
this->arr[index] = obj;
this->arrid[index] = wcstrdup(id);
return index;
}
template<class T> T*& HashContainer<T>::operator [] (const TCHAR* id)
{
int index = this->GetIndex(id);
if (index < 0) index = Add(id, 0);
return (this->arr[index]);
}
template<class T> T*& HashContainer<T>::operator [] (int index)
{
if (index < 0 || index >= this->arrCount) throw L"HashContainer: Index Out Of Bounds";
return (this->arr[index]);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -