什么是一个好的哈希函数的结构与3个unsigned字符和一个int,对于unordered_map? [英] What's a good hash function for struct with 3 unsigned chars and an int, for unordered_map?

查看:138
本文介绍了什么是一个好的哈希函数的结构与3个unsigned字符和一个int,对于unordered_map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想使用一个unordered_map与我的结构作为键,因为我不需要任何排序。但我只是不能找到自己与所有的哈希的东西..

I just want to use a unordered_map with my struct as key, since I dont need any ordering..but I just cant find myself with all that hash stuff..

作为一个相关的问题。当ppl比较无序和有序映射他们从来没有谈到哈希函数,怎么可能?不好的哈希函数使无序映射比map慢? (仅由于散列函数)

As a side relevant question..When ppl compare unordered and ordered map they never talk about the hash function, how can that be? Cant a bad hash function makes unordered map slower than map? (solely due the hash function)

struct exemple{

  unsigned char a,b,c;
  unsigned int n;

  bool operator == ( const exemple & other) const {..}
};

namespace std {
template <>
struct hash<exemple> : public std::unary_function<const exemple &, std::size_t>
{
    inline std::size_t operator()(const exemple & exemple_p ) const
    {
        return 0;// what do I do
    }
};

}

-edit-
a,b,c只能有值'a','b','c'或'd',而n的变化范围为3〜60。

-edit- a,b,c can have only the values 'a', 'b', 'c' or 'd', and n varies ~ 3 to 60.

推荐答案

在散列函数中做什么取决于你获得的值,不一定取决于它们的类型。如果所有四个数据成员包含均匀分布的每个值,我将把两个字符组合成 unsigned long ,并返回两个值的匹配结果:

What you do in your hash function depends on the values you got, not necessarily so much on their types. If all four data members contain each value evenly distributed, I would combine the two characters into an unsigned long and return the result of xoring the two values:

typedef unsigned long ulong;
return n ^ (ulong(a << 16) | ulong(b << 8) | ulong(c));

这是一个哈希函数。是否是一个工作良好是一个不同的问题。您还可以将结果与 std :: hash< unsigned long> 组合。

这篇关于什么是一个好的哈希函数的结构与3个unsigned字符和一个int,对于unordered_map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆