1. header file
#pragma once
template<typename KEY, typename VALUE>
class CMap
{
struct SNode
{
KEY key;
VALUE value;
SNode* pLeft, *pRight;
SNode(KEY &key, VALUE &value) :key(key), value(value)
{
pLeft = pRight = nullptr;
}
};
SNode* m_pRoot;
int m_nCount;
public:
void SetAt(KEY key, VALUE value);
bool LookUp(KEY key, VALUE rValue) const;
VALUE& operator[](KEY key);
void RemoveAll(SNode* p);
int GetCount() const
{
return m_nCount;
}
CMap();
virtual ~CMap();
};
template<typename KEY, typename VALUE>
CMap<KEY, VALUE>::CMap():m_nCount(0)
{
m_pRoot = nullptr;
}
template<typename KEY, typename VALUE>
CMap<KEY, VALUE>::~CMap()
{
if (m_pRoot)
RemoveAll(m_pRoot);
m_pRoot = nullptr;
m_nCount = 0;
}
template<typename KEY, typename VALUE>
void CMap<KEY, VALUE>::SetAt(KEY key, VALUE value)
{
operator[](key) = value;
}
template<typename KEY, typename VALUE>
bool CMap<KEY, VALUE>::LookUp(KEY key, VALUE rValue) const
{
SNode* p = m_pRoot;
while (p)
{
if (key < p->key)
p = p->pLeft;
else if (key > p->key)
p = p->pRight;
else
{
rValue = p->value;
return true;
}
}
return false;
}
template<typename KEY, typename VALUE>
VALUE& CMap<KEY, VALUE>::operator[](KEY key)
{
SNode* *p = &m_pRoot;
while (*p)
{
if (key < (*p)->key)
p = &((*p)->pLeft);
else if (key >(*p)->key)
p = &((*p)->pRight);
else
return (*p)->value;
}
*p = new SNode(key, VALUE());
++m_nCount;
return (*p)->value;
}
template<typename KEY, typename VALUE>
void CMap<KEY, VALUE>::RemoveAll(SNode* p)
{
if (p->pLeft)
RemoveAll(p->pLeft);
if (p->pRight)
RemoveAll(p->pRight);
delete p;
m_nCount = 0;
}