博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
STL: unordered_map 自定义键值使用
阅读量:4625 次
发布时间:2019-06-09

本文共 1800 字,大约阅读时间需要 6 分钟。

使用Windows下 RECT 类型做unordered_map 键值

1. Hash 函数

 计算自定义类型的hash值。

struct hash_RECT {	size_t operator()(const RECT &rc) const	{		return std::_Hash_seq((const unsigned char *)&rc, sizeof(RECT));	}};

  

2. 相等函数

 哈希需要处理碰撞,意味着必须判断两个自定义类型对象是否相等。

struct cmp_RECT{	bool operator()(const RECT &rc1, const RECT &rc2) const	{		return rc1.left == rc2.left && rc1.top == rc2.top			&& rc1.right == rc2.right && rc1.bottom == rc2.bottom;	}};

  

3. 使用

std::unordered_map
G_mapText

 这样感觉好长,我们接着往下看。

 

4. 使用STL提供的模板

stl中有这么两个模板

// TEMPLATE STRUCT _Bitwise_hashtemplate
struct _Bitwise_hash { // hash functor for plain old data typedef _Kty argument_type; typedef size_t result_type; size_t operator()(const _Kty& _Keyval) const { // hash _Keyval to size_t value by pseudorandomizing transform return (_Hash_seq((const unsigned char *)&_Keyval, sizeof (_Kty))); } }; // TEMPLATE STRUCT hashtemplate
struct hash : public _Bitwise_hash<_Kty> { // hash functor for enums static const bool _Value = __is_enum(_Kty); static_assert(_Value, "The C++ Standard doesn't provide a hash for this type."); };

所以我们可以直接这么写:

std::unordered_map
, cmp_RECT> G_mapText

这样就可以丢掉上面的 hash函数 “hash_RECT”  

这样写感觉还是比较长,我们再来看看另一种方法。

 

4. 实例化模板

直接实例化模板,这样的话使用 unordered_map 时便不用再指定 Hash 函数,但要求必须为 KEY 重载 operator ==,实例化模板如下:

namespace std{	template<>	struct hash
: public _Bitwise_hash
{ // hash functor for RECT }; inline bool operator == (const RECT &rc1, const RECT &rc2) _NOEXCEPT { return rc1.left == rc2.left && rc1.top == rc2.top && rc1.right == rc2.right && rc1.bottom == rc2.bottom; }}

这样我们就可以直接这么写了:

std::unordered_map
G_mapText;

 

实例代码:

 

至此 unordered_map 自定义键值的用法结束。

 

转载于:https://www.cnblogs.com/kindly/p/6023949.html

你可能感兴趣的文章
crm创建报告补充导航
查看>>
几种开源分词工具的比較
查看>>
等于null和长度0有区别,null不能调用任何方法,如Tostring 和.length 源于checkbox的未勾选返回值为null,勾选的返回值为on...
查看>>
项目管理专业 知识点总结(三)
查看>>
关于Android 打开新的Activity 虚拟键盘的弹出与不弹出
查看>>
“万能数据库查询分析器”在四大软件下载网站的排行榜中均入围前10,可喜可贺...
查看>>
和菜鸟一起学linux总线驱动之smartcard操作模式和协议与参数选择
查看>>
android 开发工具(转)
查看>>
python中的uuid4
查看>>
CSS 必知的7个知识点
查看>>
asp.net mvc 生成条形码
查看>>
单调队列
查看>>
Attribute value is quoted with " which must be escaped when used within the value 问题解决
查看>>
作业01
查看>>
web学习记录-JS-12
查看>>
ubuntu安装软件包apt-get和dpkg方法
查看>>
工作中vue项目前后端分离,调用后端本地接口出现跨域问题的完美解决
查看>>
BZOJ3894: 文理分科
查看>>
动态生成元素动作绑定,jquery 1.9如何实现
查看>>
C语言经典算法100例-032~35
查看>>