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

时间:2014-09-03 12:34:07

标签: c++ c++11 random

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

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

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

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

std::mt19937 mt;
mt.seed(seednum);

在主内部,只需将mt传递给morerandom()。我试过了:

#include <iostream>
#include <random>
int morerandom(const int nmax)
{

     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) << std::endl;
    }

    return 0;
}

但是编译器抱怨:

error: ‘mt’ was not declared in this scope return(uint(mt));

1 个答案:

答案 0 :(得分:3)

解决方案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;
}

解决方案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;
}