C++基于二叉树开发模板化CMap类

1.头文件

#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;
}


发布了21 篇原创文章 · 获赞 20 · 访问量 2942

猜你喜欢

转载自blog.csdn.net/weixin_42844163/article/details/104238246
今日推荐