【问题标题】:Fix seed globaly in c++11 <random>在 c++11 <random> 中全局修复种子
【发布时间】:2014-09-03 12:34:06
【问题描述】:

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

#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);

在 main 中,只需将 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));

【问题讨论】:

  • 编译器的抱怨是正确的,因为 mt 的名称在 morerandom 内部是未知的。请明确你想要做什么。我真的不明白你在做什么。
  • @filmore:我不知道如何将 mt 传递给函数(到处搜索却找不到!)

标签: c++ c++11 random


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多