std :: default_random_engine即使更改种子也会生成相同的值? [英] std::default_random_engine generates the same values even with changing seed?

查看:647
本文介绍了std :: default_random_engine即使更改种子也会生成相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个类,该类将充当随机库的包装器,以便在代码的其他地方(我认为)可以更直观的方式使用其对象和函数.

I'm trying to implement a class that will serve as sort of a wrapper for the random library so I can use its objects and functions in (I think) a more intuitive way elsewhere in my code.

在标题中,我有这样的东西:

In my header I have something like this:

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

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

And then in the .cpp file I implement those two functions (constructor and randInt) like so:

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中,我像下面这样测试这些功能:

Finally, in my main.cpp I test these functions like this:

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

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

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

The problem is, no matter what I set the seed to in main.cpp, I always get the same values for my random numbers (not just randInt, I have other distributions as well). I've also tried setting seed to time(NULL) but the same problem occurs.

我真的很head头.谢谢!

I'm really scratching my head at this one. Thanks!

推荐答案

default_random_engine engine;
engine.seed(n);

这为本地engine注入了种子,该本地engine在构造函数的末尾被销毁,而不是类成员engine,该成员最终被默认构造.

This is seeding the local engine, which is destroyed at the end of the constructor, not the class member engine, which ends up being default constructed.

改为使用成员初始化器列表:

Use the member initializer list instead:

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

这篇关于std :: default_random_engine即使更改种子也会生成相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆