【问题标题】:Hash function for vector<double>vector<double> 的散列函数
【发布时间】:2013-03-17 03:14:06
【问题描述】:

首先,我想知道是否有人知道表示 n 维向量的向量的散列函数?

其次,是否有一个类似的哈希函数,我可以指定一个分辨率,使两个“接近”的向量哈希到相同的值?

例如: 给定分辨率 r = 0.01 q1 = {1.01, 2.3} q2 = {1.01, 2.31} 将哈希到相同的值。

感谢您的帮助!

【问题讨论】:

  • 根据定义,这不是哈希函数。我想你可以为每一个做 floor(x*10) ,然后使用普通的散列函数。

标签: c++ algorithm hash


【解决方案1】:

也许这样的东西对你有用?

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多