向量< double& gt;的哈希函数 [英] Hash function for vector&lt;double&gt;
本文介绍了向量< double& gt;的哈希函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先,我想知道是否有人知道代表n维向量的向量的哈希函数吗?
First, I am wondering if anyone knows of a hash function for vector representing an n-D vector?
第二,是否有类似的哈希函数,我可以在其中指定分辨率,以使两个闭合"向量哈希为相同值?
Second, is there a similar hash function where I can specify a resolution such that two "close" vectors hash to the same value?
例如: 给定分辨率r = 0.01 q1 = {1.01,2.3} q2 = {1.01,2.31} 会散列为相同的值.
For example: given resolution r = 0.01 q1 = {1.01, 2.3} q2 = {1.01, 2.31} would hash to the same value.
感谢您的帮助!
推荐答案
也许这样的方法对您有用?
Perhaps something like this would work for you?
#include <stdint.h>
#include <iostream>
#include <vector>
using namespace std;
// simple variant of ELF hash ... but you could use any general-purpose hashing algorithm here instead
static int GetHashCodeForBytes(const char * bytes, int numBytes)
{
unsigned long h = 0, g;
for (int i=0; i<numBytes; i++)
{
h = ( h << 4 ) + bytes[i];
if (g = h & 0xF0000000L) {h ^= g >> 24;}
h &= ~g;
}
return h;
}
static int GetHashForDouble(double v)
{
return GetHashCodeForBytes((const char *)&v, sizeof(v));
}
static int GetHashForDoubleVector(const vector<double> & v)
{
int ret = 0;
for (int i=0; i<v.size(); i++) ret += ((i+1)*(GetHashForDouble(v[i])));
return ret;
}
int main()
{
vector<double> vec;
vec.push_back(3.14159);
vec.push_back(2.34567);
cout << " Hash code for test vec is: " << GetHashForDoubleVector(vec) << endl;
return 0;
}
这篇关于向量< double& gt;的哈希函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文