0
点赞
收藏
分享

微信扫一扫

STL之hash_map


hash_map最大的特色在于可以根据不同的数据类型进行检索,同时,这种检索是常数级别的,恩,我先写下代码吧

// hash_map.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<hash_map>
#include<iostream>
using namespace std;
struct myStr
{
int num;
};
struct strequal
{
static const size_t bucket_size = 4; // 猜测这个变量是初始化hash_map的大小
bool operator()(const myStr a, const myStr b) const
{
return a.num != b.num;
}
size_t operator ()(const myStr key)const
{
return key.num % 3;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
hash_map<myStr, float, strequal > hm;
myStr nn;

nn.num = 9;
hm[nn] = 2.0f;
pair<myStr, float>p(nn, 0.9f);
hm.insert(p);
for (hash_map<myStr, float, strequal>::iterator itr = hm.begin(); itr != hm.end(); itr++)
{
cout << itr->second << endl;
}
}

这里面呢,需要注意的就一点,就是自定义的比较函数对象中一定要有哈希函数对象,并且,参数类型一定是关键字的数据类型,才行!

hash_map同hash_set一样使用表头和单链作为数据结构,同样适用桶的概念,不同于hash_set的是hash_set的键值和真实的数据是相同的,而hash_map的键值和真实数据是不同的,同样的hash_map也是不允许插入同样的值的

见​​STL之hash_set​​



举报

相关推荐

0 条评论