哈希映射

本文介绍了一种快速的哈希映射实现方法,并与线性映射进行了对比,展示了哈希映射在查找速度上的优势。同时,文章通过实例演示了不同映射类型在C++中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#ifndef HASHMAP_H_
#define HASHMAP_H_

#include <vector>

template<class Key, class Value>
class HashMap  // 哈希映射 速度最快,
{
public:
	HashMap(int size = 100) : arr(size)
	{
		currentSize = 0;
	}
	void Put(const Key & k,const Value & v)
	{
		int pos = myhash(k);
		arr[pos] = DataEntry(k,v);
		++currentSize;
	}
	Value Get(const Key & k)  
	{
		int pos = myhash(k);
		if(arr[pos].key == k)
			return arr[pos].value;
		else
		    return Value();
	}
	unsigned hash(const Key & k) const
	{
		unsigned int hashVal = 0;
		const char *keyp = reinterpret_cast<const char *>(&k);  // 将k转变为字符,
		for(size_t i = 0; i < sizeof(Key); i++)
			hashVal = 37 * hashVal + keyp[i];
		return hashVal;
	}
	int myhash(const Key & k) const
	{
		unsigned hashVal = hash(k);
		hashVal %= arr.size();
		return hashVal;
	}
private:
	struct DataEntry
	{
		Key key;
		Value value;

		DataEntry(const Key & k = Key(),const Value & v = Value()):key(k),value(v){}
	};
	std::vector<DataEntry> arr;
	int currentSize;
};


#endif

#ifndef LINEARMAP_H_
#define LINEARMAP_H_

#include <vector>

template<class Key, class Value>
class LinearMap  // 线性映射  不使用,
{
public:
	LinearMap(int size = 100) : arr(size)
	{
		currentSize = 0;
	}
	void Put(const Key & k,const Value & v)
	{
		arr[currentSize] = DataEntry(k,v);
		++currentSize;
	}
	Value Get(const Key & k)  // 在这里可以看出它的查找速度非常的慢,
	{
		for(size_t i = 0; i < currentSize; ++i)
		{
			if(arr[i].key == k)
				return arr[i].value;
		}
		return Value();
	}
private:
	struct DataEntry
	{
		Key key;
		Value value;

		DataEntry(const Key & k = Key(),const Value & v = Value()):key(k),value(v){}
	};
	std::vector<DataEntry> arr;
	int currentSize;
};


#endif

#include <iostream>
#include <map>  // 映射(也叫字典),二叉树映射,不是哈希映射,
#include <hash_map> // 这个是C++自己做的哈希映射,是微软做的,
#include <string>
#include "LinearMap.h"
#include "HashMap.h"

using namespace std;

int main()
{
	map<string,int> m; // 这是二叉树(红黑树)映射,
	m["xiaocui"] = 88;
	m["hengheng"] = 66;

	cout << m["xiaocui"] << endl;

	cout << "数组的优点: \n";
	int a[100000];
	for(int i = 0; i < 100000; ++i)
		a[i] = i % 100;

	cout << a[7] << endl;
	cout << a[99912] << endl; // 数组的操作是对下标进行操作,速度非常的快,直接一下找到,

	LinearMap<string,int> lm;
	lm.Put("xiaocui",1314);

	cout <<"LinerMap: " << lm.Get("xiaocui") << endl;

	cout << "哈希映射:" << endl << endl;
	HashMap<string,int> mymap;

	cout << mymap.hash("xiaocui") << endl;
	cout << mymap.myhash("xiaocui") << endl;
	mymap.Put("xiaocui",9999);
	mymap.Put("cuicui",88888);
	cout << mymap.Get("cuicui") << endl;


	cout << "使用C++自己做的哈希映射:" << endl;
	hash_map<string,int> hm;
	hm["xiao"] = 12;
	hm["cui"] = 31;

	cout << hm["cui"] << endl;


	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值