我正在使用MinHash函数。我刚刚在C#中找到了一些代码但我想用C ++编写,因为我的代码是用C ++编写的。
我对lambda表达式和委托函数感到很困惑。
C#代码就像
public delegate uint Hash(int toHash);
private Hash[] hashFunctions;
// Public access to hash functions
public Hash[] HashFunctions
{
get { return hashFunctions; }
}
// Generates the Universal Random Hash functions
// http://en.wikipedia.org/wiki/Universal_hashing
private void GenerateHashFunctions(int u)
{
hashFunctions = new Hash[numHashFunctions];
// will get the same hash functions each time since the same random number seed is used
Random r = new Random(10);
for (int i = 0; i < numHashFunctions; i++)
{
uint a = 0;
// parameter a is an odd positive
while (a % 1 == 1 || a <= 0)
a = (uint)r.Next();
uint b = 0;
int maxb = 1 << u;
// parameter b must be greater than zero and less than universe size
while (b <= 0)
b = (uint)r.Next(maxb);
hashFunctions[i] = x => QHash(x, a, b, u);
}
}
// Universal hash function with two parameters a and b, and universe size in bits
private static uint QHash(int x, uint a, uint b, int u)
{
return (a * (uint)x + b) >> (32 - u);
}
我试图通过create struct翻译成C ++,但我仍然不知道如何处理这行
hashFunctions[i] = x => QHash(x, a, b, u);
C ++代码我到现在为止
struct Hash
{
// Universal hash function with two parameters a and b, and universe size in bits
unsigned int operator()(int toHash)
{
}
};
Hash* hashFunctions;
void GenerateHashFunctions(int u)
{
hashFunctions = new Hash[numHashFunction];
// will get the same hash functions each time since the same random number seed is used
for (int i = 0; i < numHashFunction; i++)
{
unsigned int a = 0;
// parameter a is an odd positive
while (a % 1 == 1 || a <= 0)
a = (unsigned int)rand()%10;
unsigned int b = 0;
int maxb = 1 << u;
// parameter b must be greater than zero and less than universe size
while (b <= 0)
b = (unsigned int)rand()%maxb;;
//hashFunctions[i] = x => QHash(x, a, b, u);
}
}
static unsigned QHash(int x,unsigned int a,unsigned int b,int u)
{
return (a * (unsigned int)x + b) >> (32 - u);
}
有人请给我一些建议吗?非常感谢你
答案 0 :(得分:2)
使用C ++ lambda表达式。
hashFunctions[i] = [=] (auto x) { return QHash(x, a, b, u); };
另外请避免使用原始指针或数组。 使用标准容器,如
std::vector<std::function<uint (int)>>
此外,您不应该使用c样式转换,例如
(unsigned)(expression)
喜欢
static_cast<unsigned>(expression)
编辑:这是一个例子:
#include <vector>
#include <functional>
....
private:
using HashProvider = std::function<uint, (int)>;
auto GenerateHashFunctions(int u)
{
auto hashFunctions = std::vector<HashProvider>(numHashFunctions);
for (int i = 0; i < numHashFunctions; i++)
{
uint a = 0;
// parameter a is an odd positive
while (a % 1 == 1 || a <= 0) {
a = static_cast<uint>(r.Next());
}
uint b = 0;
int maxb = 1 << u;
// parameter b must be greater than zero and less than universe size
while (b <= 0) {
b = static_cast<uint>(r.Next(maxb));
}
hashFunctions.push_back([=](auto x) { return QHash(x, a, b, u); });
}
return hashFunctions;
}