STL: unordered_map 自定义键值类型的使用(C++)
来源:互联网 发布:数据结构和算法的关系 编辑:程序博客网 时间:2024/06/08 18:50
当试图使用自定义类型作为 unordered_map 的键值时,则必须为自定义类型定义 Hash 函数与相等的判断条件。我们先定义自定义类型作键值,代码如下:
struct KEY{int first;int second;int third;KEY(int f, int s, int t) : first(f), second(s), third(t){}};
1. Hash 函数
必须为 override 了 operator() 的一个类,一般自定义类型可能包含几种内置类型,我们可以分别计算出内置类型的 Hash Value 然后对它们进行 Combine 得到一个哈希值,一般直接采用移位加异或(XOR)便可得到还不错的哈希值(碰撞不会太频繁),如下:
struct HashFunc{std::size_t operator()(const KEY &key) const {using std::size_t;using std::hash;return ((hash<int>()(key.first)^ (hash<int>()(key.second) << 1)) >> 1)^ (hash<int>()(key.third) << 1);}};
另外一种方法是直接实例化模板,这样的话使用 unordered_map 时便不用再指定 Hash 函数,但要求必须为 KEY 重载 operator ==,实例化模板如下:
namespace std {template <>struct hash<KEY>{std::size_t operator()(const KEY &key) const{using std::size_t;using std::hash;// Compute individual hash values for first,// second and third and combine them using XOR// and bit shifting:return ((hash<int>()(key.first)^ (hash<int>()(key.second) << 1)) >> 1)^ (hash<int>()(key.third) << 1);}};}
2. 相等函数
哈希需要处理碰撞,意味着必须得知道两个自定义类型对象是否相等,所以必须得提供比较相等的方法,可以 overload operator ==,可以用 std::equal,也可以实现一个 override operator () 的类,这里我们采用后者(这也意味着 Hash 函数不能使用实例化模板的方法,只能定义一个重载了 operator() 的类),代码如下:
struct EqualKey{bool operator () (const KEY &lhs, const KEY &rhs) const{return lhs.first == rhs.first&& lhs.second == rhs.second&& lhs.third == rhs.third;}};
3. 应用实例
下面为一个具体应用的例子
int main(){unordered_map<KEY, string, HashFunc, EqualKey> hashmap ={{ { 01, 02, 03 }, "one" },{ { 11, 12, 13 }, "two" },{ { 21, 22, 23 }, "three" },};KEY key(11, 12, 13);auto it = hashmap.find(key); if (it != hashmap.end()) { cout << it->second << endl; }return 0;}
0 0
- STL: unordered_map 自定义键值类型的使用(C++)
- 【map】【unordered_map】map和unordered_map中键类型为自定义类型的操作
- (未解决)牛客 题库 STL中的unordered_map和priority_queue使用的底层数据结构分别是什么?()
- C++unordered_map使用例子
- 【leetcode】Two Sum(unordered_map的使用)
- hash_map,unordered_map的使用
- unordered_map的使用
- STL map/ unordered_map/ vector内存使用实验
- map 自定义类型作为键值
- STL map与Boost unordered_map 的不同
- STL map和unordered_map的区别
- STL中map,unordered_map,multimap的区别
- STL学习----入门(1)[unordered_map]
- map以自定义类型当Key(键值)
- map以自定义类型当Key(键值)
- map以自定义类型当Key(键值)
- c#Dictionary键值对的使用
- hash_map和unordered_map的使用
- android 常用图表
- Oracle导入dmp备份文件到不同的表空间中
- abstract class和interface的区别
- POJ 2528 Mayor's posters 线段树区间更新+离散化
- OPENWRT的若干命令
- STL: unordered_map 自定义键值类型的使用(C++)
- 集成学习——Boosting和Bagging
- Interceptor详解
- CSS基础学习十:伪元素
- Mybatis 中用# 和 $ 的区别
- android 如何解析XML
- MD5加密 C#窗体应用程序
- Java HMACShA256
- poj 2584 T-Shirt Gumbo