修复 c++11 中的全局种子 <random>

use*_*035 4 c++ random c++11

我正在尝试使用新的c++ <random>标头与全局固定种子一起使用。这是我的第一个玩具示例:

\n\n
#include <iostream>\n#include <random>\nint morerandom(const int seednum,const int nmax){\n     std::mt19937 mt;\n     mt.seed(seednum);\n     std::uniform_int_distribution<uint32_t> uint(0,nmax);\n     return(uint(mt));\n}\nint main(){\n    const int seed=3;\n    for (unsigned k=0; k<5; k++){\n        std::cout << morerandom(seed,10) << std::endl;\n    }\n    return 0;\n} \n
Run Code Online (Sandbox Code Playgroud)\n\n

所以问题是:如何修复 中的种子main()并从 \n 中获得可重现的输出morerandom()

\n\n

换句话说,我需要调用morerandom()很多(k会很大),但这些随机数应该始终使用相同的值来绘制seed. 我想知道定义整个块是否可能/更有效:

\n\n
std::mt19937 mt;\nmt.seed(seednum);\n
Run Code Online (Sandbox Code Playgroud)\n\n

在 main 内部并传递mtmorerandom(). 我尝试过:

\n\n
#include <iostream>\n#include <random>\nint morerandom(const int nmax)\n{\n\n     std::uniform_int_distribution<uint32_t> uint(0,nmax);\n     return(uint(mt));\n}\n\n\nint main()\n{\n    const int seed=3;\n    std::mt19937 mt;\n    mt.seed(seed);\n    for (unsigned k=0; k<5; k++)\n    {\n\n        std::cout << morerandom(10) << std::endl;\n    }\n\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但编译器抱怨:

\n\n
error: \xe2\x80\x98mt\xe2\x80\x99 was not declared in this scope return(uint(mt));\n
Run Code Online (Sandbox Code Playgroud)\n

Pio*_*cki 6

解决方案1

#include <iostream>
#include <random>

int morerandom(const int nmax, std::mt19937& mt)
//                             ^^^^^^^^^^^^^^^^
{    
     std::uniform_int_distribution<uint32_t> uint(0,nmax);
     return(uint(mt));
}    

int main()
{
    const int seed=3;
    std::mt19937 mt;
    mt.seed(seed);
    for (unsigned k=0; k<5; k++)
    {    
        std::cout << morerandom(10, mt) << std::endl;
        //                          ^^
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

解决方案2

#include <iostream>
#include <random>

std::mt19937 mt;
// ^^^^^^^^^^^^^

int morerandom(const int nmax)
{    
     std::uniform_int_distribution<uint32_t> uint(0,nmax);
     return(uint(mt));
}    

int main()
{
    const int seed=3;
    mt.seed(seed);
    for (unsigned k=0; k<5; k++)
    {    
        std::cout << morerandom(10) << std::endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)