簡體   English   中英

Mersenne Twister種子作為成員變量

[英]Mersenne Twister seed as a member variable

我想知道如何將mersenne隨機數生成器保留為成員變量,並在同一類中使用它。

我按照下面的方式編寫了該類,它可以完美運行,但是我不喜歡std::mt19937的初始化。 我想知道在Test的構造函數中是否有初始化它的方法?

#include <iostream>
#include <cmath>
#include <random>
#include <chrono>
#include <ctime>

class Test{
public:
    Test()
    {

    }
    void foo()
    {
        auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
    }

private:
    std::mt19937 rnd
    {
        std::chrono::high_resolution_clock::now().time_since_epoch().count()
    };
}

我想您對類初始化的確切作用感到困惑。 當你有

struct foo
{
    foo() {}
    int bar = 10;
};

在類中初始化只是語法糖

struct foo
{
    foo() : bar(10) {}
    int bar;
};

每當編譯器將成員添加到成員初始值設定項列表時(當您忘記它或當編譯器提供了構造函數時便會這樣做),它將使用初始化中使用的內容。 所以用你的代碼

class Test{
public:
    Test()
    {

    }
    void foo()
    {
        auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
    }

private:
    std::mt19937 rnd
    {
        std::chrono::high_resolution_clock::now().time_since_epoch().count()};
    };
};

class Test{
public:
    Test() : rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count())
    {

    }
    void foo()
    {
        auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
    }

private:
    std::mt19937 rnd;
};

關於不實際使用該方法並使用它的開始方式的好處是您不必重復

rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count())

在您編寫的每個構造函數中,但是如果您想要特定構造函數的其他內容,則可以始終覆蓋它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM