#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;
}
简单运用Hash_map
最新推荐文章于 2023-11-09 10:50:40 发布