简单运用Hash_map

#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS 1       //在VisalStudio2017上运行时报不安全加上
#include<iostream>
#include<string>
#include<hash_map>

using namespace std;

struct MyHash       //自定义hash函数与比较函数
{
	size_t operator()(const string &str)const   //hash函数
	{
		unsigned long h = 0;
		for (size_t i = 0; i < str.size(); i++)
			h = 5 * h + str[i];

		return size_t(h);    //注意返回类型是size_t
	}
			
	bool operator()(const string &hs, const string &ht)
	{
		return !(ht == hs); //注意:当判断是相同的时候返回false
	}

	static const size_t bucket_size = 4;   //注意添加这个静态成员,是表大小的预设值,会自动增加
	

};


int main()
{
	hash_map<string, int, MyHash> A;
	int i;
	i = A["hello"];         //在这句hash表就会增加hello,值初始为0,即只要有访问hash时不存在就会自动添加
	A["hello"] = 10;         //修改值
	cout << A["hello"] << endl;
	system("pause");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值