自定义哈希函数

来源:互联网 发布:手机在线视频录制软件 编辑:程序博客网 时间:2024/06/13 08:43

每种数据类型都需要相应的 hash function。在C++中,一些内置类型不需要自定义哈希函数,例如,int,double,string等。但是一些自定义的数据类型就需要自定义哈希函数了。例如,下面定义了直线Line,根据y=kx+b,每条直线需要两个变量来定义:kb

注意,除了定义哈希函数外,记得还要重载==运算符,也就是定义等于操作。

#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