C++ 一对长函数的哈希函数?

C++ 一对长函数的哈希函数?,c++,hash,tr1,unordered-map,hash-function,C++,Hash,Tr1,Unordered Map,Hash Function,我需要将一对long映射为一对double,但我不确定要使用什么哈希函数。每对数字可以由任意两个数字组成,尽管在实践中它们通常是介于0和大约100之间的数字(但这也不能保证) 是tr1::无序图文档。我是这样开始的: typedef long long Int; typedef std::pair<Int, Int> IntPair; struct IntPairHash { size_t operator(const IntPair& p) const { r

我需要将一对
long
映射为一对
double
,但我不确定要使用什么哈希函数。每对数字可以由任意两个数字组成,尽管在实践中它们通常是介于
0
和大约
100
之间的数字(但这也不能保证)

tr1::无序图
文档。我是这样开始的:

typedef long long Int;
typedef std::pair<Int, Int> IntPair;

struct IntPairHash {
  size_t operator(const IntPair& p) const {
    return ...; // how to hash the pair?
  }
};

struct IntPairEqual {
  bool operator(const IntPair& a, const IntPair& b) const {
    return a.first == b.first 
      && a.second == b.second;
  }
};

tr1::unordered_map<IntPair, double, IntPairHash, IntPairEqual> myMap;
size_t seed = ah(p.first);
return bh(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);
typedef long long Int;
typedef std::pair IntPair;
结构IntPairHash{
大小运算符(常量IntPair&p)常量{
return…;//如何散列该对?
}
};
内部结构{
布尔运算符(常数对与a、常数对与b)常数{
返回a.first==b.first
&&a.second==b.second;
}
};
tr1::无序的地图myMap;

一般来说,我不确定使用什么样的散列函数。什么是好的通用哈希函数?

您真的需要基于哈希的映射吗?基于二叉树的通用映射可以很好地工作,只要它的复杂性能够保证它对您正在解决的问题起作用。

建议:看看这篇文章:

此外,上的Boost文档也是一个很好的地方(以及这个)。

表单函数库


或者写你自己的。最简单的版本=pair.first*max_second_value+pair.second散列对的自然方式是以某种方式组合其组件的散列。最简单的方法就是使用xor:

namespace std {
namespace tr1 {

template<typename a, typename b>
struct hash< std::pair<a, b> > {
private:
   const hash<a> ah;
   const hash<b> bh;
public:
   hash() : ah(), bh() {}
   size_t operator()(const std::pair<a, b> &p) const {
      return ah(p.first) ^ bh(p.second);
   }
};

}} // namespaces
名称空间std{
名称空间tr1{
模板
结构哈希{
私人:
const hash ah;
常量散列bh;
公众:
hash():ah(),bh(){}
size_t运算符()(常数std::pair&p)常数{
返回ah(第一页)^bh(第二页);
}
};
}}//名称空间
请注意,这会将(1,1)或(2,2)等散列对全部置零,因此您可能需要使用更复杂的方式来组合各部分的散列,具体取决于您的数据。Boost的功能如下:

typedef long long Int;
typedef std::pair<Int, Int> IntPair;

struct IntPairHash {
  size_t operator(const IntPair& p) const {
    return ...; // how to hash the pair?
  }
};

struct IntPairEqual {
  bool operator(const IntPair& a, const IntPair& b) const {
    return a.first == b.first 
      && a.second == b.second;
  }
};

tr1::unordered_map<IntPair, double, IntPairHash, IntPairEqual> myMap;
size_t seed = ah(p.first);
return bh(p.second) + 0x9e3779b9 + (seed<<6) + (seed>>2);
size\u t seed=ah(p.first);
返回bh(p.second)+0x9e3779b9+(seed2);

Hmm好的,在这种情况下,比较两个整数对的比较函数(整数对的
less
函数)是什么样子的?@Frank:最简单的形式:(a.first(a.first
不是一个命令。配对(1,0)和(0,1)在这个“排序”中是不同的和不可比较的。您是否考虑过使用以下一个或多个通用哈希函数:它们非常快速和高效。请仔细阅读boost hash.hpp。Bost的操作如下:seed=hash(first)+0x9e3779b9+(seed2);返回seed^(散列(第二个)+0x9e3779b9+(seed2));