hashmap
来源:互联网 发布:oracle 监控软件 编辑:程序博客网 时间:2024/06/10 11:09
#include <hash_map>
#include <string>
using namespace std;
int main(){
够简单,和map使用方法一样。这时你或许会问?hash函数和比较函数呢?不是要指定么?你说对了,但是在你没有指定hash函数和比较函数的时候,你会有一个缺省的函数,看看hash_map的声明,你会更加明白。下面是SGI STL的声明:
template <class _Key, class _Tp, class _HashFcn = hash<_Key>,
class _EqualKey = equal_to<_Key>,
class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >
class hash_map
{
}
也就是说,在上例中,有以下等同关系
hash_map<int, string> mymap;
//等同于:
hash_map<int, string, hash<int>, equal_to<int> > mymap;
Alloc我们就不要取关注太多了(希望深入了解Allocator的朋友可以参看标准库 STL :Allocator能做什么)
2.2 hash_map 的hash函数
hash< int>到底是什么样子?看看源码:
struct hash<int> {
};
原来是个函数对象。在SGI STL中,提供了以下hash函数:
struct hash<char*>
struct hash<signed char>
struct hash<unsigned int> struct hash<long> struct hash<unsigned long>
也就是说,如果你的key使用的是以上类型中的一种,你都可以使用缺省的hash函数。当然你自己也可以定义自己的hash函数。对于自定义变量,你只能如此,例如对于string,就必须自定义hash函数。例如:
struct str_hash{
};
//如果你希望利用系统定义的字符串hash函数,你可以这样写:
struct str_hash{
};
在声明自己的哈希函数时要注意以下几点:
- 使用struct,然后重载operator().
- 返回是size_t
- 参数是你要hash的key的类型。
- 函数是const类型的。
如果这些比较难记,最简单的方法就是照猫画虎,找一个函数改改就是了。
现在可以对开头的"岳不群"进行哈希化了 . 直接替换成下面的声明即可:
map<string, string> namemap;
//改为:
hash_map<string, string, str_hash> namemap;
其他用法都不用边。当然不要忘了吧str_hash的声明以及头文件改为hash_map。
- HashMap
- HashMap
- HashMap
- HashMap
- HashMap
- HashMap
- HashMap
- HashMap
- HashMap
- HashMap
- HashMap
- hashmap
- HashMap
- HashMap
- HashMap
- hashmap
- HashMap
- Hashmap
- UNIX 的开关机等命令
- 【学习笔记】zedboard 按键中断
- uiview和CALayer 区别2
- Ext中Date format含义
- 字符串固定字节换行
- hashmap
- HTTP请求和响应过程
- 关于怎样使用three.js的小教程<一>
- maven 建立本地仓库
- 实用LLDB命令
- jQuery学习笔记1
- SecureCRT MAC OS 破解
- C#查找判断素数(埃拉托斯特尼筛法C#实现)BitArray
- 2013,互联网十大关键词