C++基于哈希表开发模板化CMap类

1.头文件

#pragma once
#include <assert.h>
#include <memory.h>
template<class KEY, class VALUE, class ARG_VALUE=const VALUE&>
class CMap
{
	struct SNode
	{
		KEY key;
		VALUE value;
		SNode* pNext;
	};
	SNode** m_hash;
	int m_nBlockSize;//头节点数量
	int m_nElemCount;//元素总数量
public:
	void SetAt(KEY key, ARG_VALUE value);
	bool LookUp(KEY key, VALUE& value) const;
	VALUE& operator[](KEY key);
	bool RemoveKey(KEY key);
	void RemoveAll();
	int GetCount() const
	{
		return m_nElemCount;
	}
	bool IsEmpty() const
	{
		return m_nElemCount==0;
	}
	CMap(int nCount=17);
	~CMap();
};
template<class KEY, class VALUE, class ARG_VALUE = const VALUE&>
CMap<KEY, VALUE, ARG_VALUE>::CMap(int nCount):m_nElemCount(0)
{
	m_hash = new SNode*[nCount];
	memset(m_hash, '\0', sizeof(SNode*)*nCount);
	m_nBlockSize = nCount;
}

template<class KEY, class VALUE, class ARG_VALUE = const VALUE&>
CMap<KEY, VALUE, ARG_VALUE>::~CMap()
{
	RemoveAll();
}
template<class KEY, class VALUE, class ARG_VALUE = const VALUE&>
void CMap<KEY, VALUE, ARG_VALUE>::SetAt(KEY key, ARG_VALUE value)
{
	operator[](key) = value;
}
template<class KEY, class VALUE, class ARG_VALUE = const VALUE&>
bool CMap<KEY, VALUE, ARG_VALUE>::LookUp(KEY key, VALUE& value) const
{
	int n = key%m_nBlockSize;
	SNode* p = m_hash[n];
	while (p)
	{
		if (p->key == key)
		{
			value = p->value;
			return true;
		}
		p = p->pNext;
	}
	return false;
}
template<class KEY, class VALUE, class ARG_VALUE = const VALUE&>
VALUE& CMap<KEY, VALUE, ARG_VALUE>::operator[](KEY key)
{
	int n = key%m_nBlockSize;
	SNode* *p = &m_hash[n];
	while (*p)
	{
		if ((*p)->key == key)
			return (*p)->value;
		p = &((*p)->pNext);
	}
	SNode* pNew = new SNode;
	pNew->key = key;
	pNew->pNext = NULL;
	*p = pNew;
	++m_nElemCount;
	return pNew->value;
}
template<class KEY, class VALUE, class ARG_VALUE = const VALUE&>
bool CMap<KEY, VALUE, ARG_VALUE>::RemoveKey(KEY key)
{
	int n = key%m_nBlockSize;
	if (!m_hash[n])
		return false;
	SNode* *p = &m_hash[n];
	while (*p)
	{
		if ((*p)->key == key)
			break;
		p = &((*p)->pNext);
	}
	if (!*p)
		return false;
	SNode* q = *p;
	*p = (*p)->pNext;
	delete q;
	--m_nElemCount;
	return true;
}
template<class KEY, class VALUE, class ARG_VALUE = const VALUE&>
void CMap<KEY, VALUE, ARG_VALUE>::RemoveAll()
{
	int i = 0;
	while (i<m_nBlockSize)
	{
		SNode *pHead = m_hash[i];
		while (pHead)
		{
			SNode* p = pHead;
			pHead = pHead->pNext;
			delete p;
		}
		m_hash[i++] = NULL;
	}
	m_nElemCount = 0;
}

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

猜你喜欢

转载自blog.csdn.net/weixin_42844163/article/details/104196941