std::default_random_engine 即使改变种子也会生成相同的值?

std::default_random_engine generates the same values even with changing seed?

我正在尝试实现一个 class,它将作为随机库的一种包装器,以便我可以使用它的 objects 和函数(我认为)更直观的方式在我的代码的其他地方。

在我的 header 我有这样的东西:

class RandomDevice{
private:
    unsigned long rand_seed;
    default_random_engine engine;
public:
    RandomDevice(unsigned long n);
    int randInt(int min, int max);};

然后在 .cpp 文件中我实现了这两个函数(constructor 和 randInt),如下所示:

RandomDevice::RandomDevice(unsigned long n){
    rand_seed = n;
    default_random_engine engine;
    engine.seed(n);
}

int RandomDevice::randInt(int min, int max){
    uniform_int_distribution<int> distribution(min, max);
    return distribution(engine);
}

最后,在我的 main.cpp 中,我像这样测试这些函数:

int main(){
    unsigned long seed = 1;
    RandomDevice my_rand(seed);

    cout << "random integer: " << my_rand.randInt(0, 10) << endl;
}

问题是,无论我在 main.cpp 中将种子设置为什么,我的随机数总是得到相同的值(不仅仅是 randInt,我还有其他分布)。我也试过将种子设置为 time(NULL) 但同样的问题出现了。

这个问题我真的很头疼。谢谢!

default_random_engine engine;
engine.seed(n);

这是局部 engine 的播种,它在构造函数结束时被销毁,而不是 class 成员 engine,它最终被默认构造。

改为使用成员初始值设定项列表:

RandomDevice::RandomDevice(unsigned long n) : rand_seed(n), engine(n){ }

尝试使用 std::chrono 在每次迭代或每次调用中提供种子。我认为播种时刻会提供最好的随机性,因为每个时刻都是独一无二的种子,没有任何重复。我会做以下事情:

#include <chrono> 
...
default_random_engine engine; // or any other engine
engine.seed(std::chrono::system_clock::now().time_since_epoch().count());

在你的构造函数中,新 created local engine 掩盖了你的 private class memeber engine.
只需删除 RandomDevice::RandomDevice() 的第二行,就可以了。

像这样。

RandomDevice::RandomDevice(unsigned long n){
    rand_seed = n;
    engine.seed(n);
}

或使用成员初始化列表作为@T.C。说,

RandomDevice::RandomDevice(unsigned long n): rand_seed(n), engine(n) { }