自定义哈希函数
来源:互联网 发布:手机在线视频录制软件 编辑:程序博客网 时间:2024/06/13 08:43
每种数据类型都需要相应的 hash function。在C++中,一些内置类型不需要自定义哈希函数,例如,int,double,string等。但是一些自定义的数据类型就需要自定义哈希函数了。例如,下面定义了直线Line
,根据
注意,除了定义哈希函数外,记得还要重载==
运算符,也就是定义等于操作。
#include <iostream>#include <unordered_map>using namespace std;//Definition for a point.struct Point { int x; int y; Point() : x(0), y(0) {} Point(int a, int b) : x(a), y(b) {}};// Definition for a line.struct Line { // y = kx + b; double slope; // k double b; // b Line (double s, double b):slope(s),b(b){};};// Custom equal operator.bool operator==(const Line& lhs, const Line& rhs) { return lhs.slope == rhs.slope && lhs.b == rhs.b;}// Custom hash function.namespace std{ template <> struct hash<Line> { size_t operator()(Line const& line) const { using std::hash; using std::size_t; size_t hashc = 17; hashc = hashc * 31 + hash<double>() (line.slope); hashc = hashc * 31 + hash<double>() (line.b); return hashc; } };}int main() { typedef unordered_map<Line, int> LineMap; LineMap lineMap; Line line(1.5, 1); lineMap[line] = 1; return 0;}
另外,可以参考Leetcode 第149题,我的解题。
0 0
- 自定义哈希函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数:
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- 自定义函数
- HTML&CSS基础学习笔记1.26-input标签重置表单
- 关于Activity和Fragment的一些问题
- [2016/8/23]TCP/IP基础
- 同机器启动多台tomcat
- strust2-学习(一)框架搭建和简单示例
- 自定义哈希函数
- 数据库连接池概念
- svn如何提交.so文件
- Spring MVC 启动报错,java.lang.NoSuchMethodError: org.springframework.core.GenericTypeResolver.resolveTyp
- JVM垃圾收集器--概述
- Java中的类与继承
- podfile模板写法与iOS最常用三方框架
- java获取指定日期前一天和后一天的日期
- Jquery $("input:checkbox[name='xxx']:checked)的含义