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



我正在尝试编写一些代码,这些代码将使用随机生成器,但允许您对其进行种子处理(以提高可复制性(。

代码看起来如下(试图创建一个可以运行的代码段(

#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, %un", i, h_k.get_a(), h_k.get_b());
}
}

我希望每个CarterWegmanHash对象都能够具有来自unif_rand的不同种子,但(毫不奇怪(,它们都是相同的。

通过指针给我error: no matching function for call to ‘CarterWegmanHash::CarterWegmanHash,通过裁判给我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));