将 uniform_int_distribution 作为参数传递(带状态)

Passing uniform_int_distribution as parameter (with state)

我正在尝试编写一些代码,这些代码将使用随机生成器,但允许您对其进行播种(为了可重现性)。

代码如下所示(尝试创建一个可以 运行 的片段)

#include <cstdio>                                      
#include <functional>
#include <random>

class CarterWegmanHash {
 private:
  unsigned int a_;
  unsigned int b_;

 public:
  // What should the signature of this be?
  CarterWegmanHash(int k, std::function<unsigned int()> unif_rand) {
    // Other stuff
    a_ = unif_rand();
    b_ = unif_rand();
  }
  unsigned int get_a() { return a_; }
  unsigned int get_b() { return b_; }
};

int main() {
  // Construct our uniform generator
  int n = 8;
  std::random_device rd;                                                        
  auto unif_rand = std::bind(                                                   
      // uniform rand from [0, n - 1]                                           
      std::uniform_int_distribution<unsigned int>(0, pow(2, n)),                
      std::mt19937(rd()));                                                      

  for (int i = 0; i < 5; ++i) {
    // How do I call this?
    CarterWegmanHash h_k(n, unif_rand);
    printf("seeds for h_%d are %u, %u\n", i, h_k.get_a(), h_k.get_b());
  }
}

我希望每个 CarterWegmanHash 对象能够具有与 unif_rand 不同的种子,但是(不出所料),它们都是相同的。

通过指针传递给我 error: no matching function for call to ‘CarterWegmanHash::CarterWegmanHash,通过 ref 传递给我 cannot bind non-const lvalue reference of type ‘std::function<unsigned int()>&’ to an rvalue of type ‘std::function<unsigned int()>’

有没有办法传递像 uniform_int_distribution 这样的随机数生成器来维持状态?

您可以在 main 中创建您的发行版和 mt19937 并在 lambda 中捕获它们:

std::uniform_int_distribution<unsigned int> distribution(0, pow(2, n));
std::mt19937 mt(rd());
auto unif_rand = [&](){ return distribution(mt); };

bind:

auto unif_rand = std::bind(std::ref(distribution), std::ref(mt));