我正在嘗試撰寫一些將使用隨機生成器但允許您播種它的代碼(為了可重復性)。
代碼如下所示(嘗試創建可以運行的代碼段)
#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這樣通過亂數生成器保持狀態?
uj5u.com熱心網友回復:
您可以創建您的發行版并mt19937在mainlambda 中捕獲它們:
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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425978.html
上一篇:使用Enum表示天數
