2015-11-24 2 views
1

Я занимаюсь функцией MinHash. Я только что нашел код на C#, но я хочу писать на C++ из-за того, что мой существующий код находится на C++.Как перевести выражение Лямбда в C# на C++

Я довольно смущен насчет выражения лямбда и функции делегата.

В # коды 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); 
} 

Я попытался перевести на C++ путем создания-структуру, но я до сих пор не знаю, что делать с этой линией

hashFunctions[i] = x => QHash(x, a, b, u); 

C++ код I до сих пор

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

Кто-нибудь, пожалуйста, дайте мне совет? Большое спасибо

ответ

2

Используйте выражение лямбда C++.

hashFunctions[i] = [=] (auto x) { return QHash(x, a, b, u); }; 

Также, пожалуйста, не используйте сырые указатели или массивы. Используйте стандартный контейнер, такой как

std::vector<std::function<uint (int)>> 

Кроме того, вы не должны использовать с стиль отбрасывает такие как

(unsigned)(expression) 

предпочитают

static_cast<unsigned>(expression) 

Edit: Вот пример:

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

Большое спасибо. Я проверю это. –

+0

minHash.cpp: В функции-члена 'void MinHash :: GenerateHashFunctions (int)': minHash.cpp: 51: 21: error: нет соответствия для 'operator =' (типы операндов: «MinHash :: Hash» и «MinHash» :: GenerateHashFunctions (int) :: ') hashFunctions [i] = [=] (авто x) {return QHash (x, a, b, u); }; } ^^ ^ struct Hash ^ –

+0

Какой компилятор вы используете? Также обратите внимание, что вам нужно будет изменить тип элемента hashFunctions. –

Смежные вопросы