基于低层哈希表的key-value容器(map容器)

template<typename T,typename V>
struct LNode {
	T key;
	V value;
	LNode * next;
	LNode(const T m_key, const V m_value) :key(m_key), value(m_value), next(nullptr) {};
};

template<typename T, typename V>
class hash_map
{
public:
	void insert(T key, V value) {
		long hashValue = std::hash<T>()(key);//获取哈希值
		int hashKey = hashValue % HASH_NUM;//获取哈希索引
		LNode<T, V>* pNode = new LNode<T, V>(key, key);//构造插入的节点 K-V
		LNode<T, V>* LocalHash = HashTable[hashKey];//查看哈希表位置
		if (LocalHash == NULL) {//位置为空 直接插入
			HashTable[hashKey] = pNode;
		}
		else {//不为空 开链法
			LNode<T, V>* InsetHashLocal = nullptr;//记录最后一个链表的位置
			while (LocalHash != nullptr) {
				InsetHashLocal = LocalHash;
				LocalHash = LocalHash->next;//寻找链表最后位置
			}
			InsetHashLocal->next = pNode;//插入构造的节点
			LocalHash = pNode;//改变链表指针
		}
	}

	pair<T,V>find(T key) {
		long hashValue = std::hash<T>()(key);//获取哈希值
		int hashKey = hashValue % HASH_NUM;//获取哈希索引
		LNode<T, V>* node = HashTable[hashKey];//查看哈希表位置
		while (node != nullptr)//顺着链表寻找
		{
			if (node->key == key) {//找到对应的key
				cout << key << "," << node->value << endl;
				return { node->key,node->value };
			}
			node = node->next;
		}
		cout << "not find K-V data" << endl;
		return {-1,-1};
	}
	void remove(T key) {
		long hashValue = std::hash<T>()(key);//获取哈希值
		int hashKey = hashValue % HASH_NUM;//获取哈希索引
		LNode<T, V>* node = HashTable[hashKey];
		while (node != nullptr) {
			LNode<T, V>* temp = nullptr;
			if (node->key != key) {
				temp = node;
				node = node->next;
			}
			else{
				if (node->next) {
					temp->next = node->next;
				}
				else {
					temp->next = nullptr
				}
				break;
			}
			
		}
	}
	void print() {
		for (int i = 0; i < HASH_NUM; i++) {
			LNode<T, V>* node = HashTable[HASH_NUM];
			cout << i << ":";
			while (node != nullptr) {
				cout << "(" << node->key << "," << node->value << ")";
				node->next;
			}
			cout << endl;
		}
	}


private:
	LNode<T, V>*  HashTable[HASH_NUM];
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值