C++:随机数生成器(random-number generator) 详解
当前位置:以往代写 > C/C++ 教程 >C++:随机数生成器(random-number generator) 详解
2019-06-13

C++:随机数生成器(random-number generator) 详解

C++:随机数生成器(random-number generator) 详解

随机数, C语言的函数是rand(), C++则是随机数生成器(random-number generator) = 漫衍工具(distribution object) + 引擎(engine);

使函数每次生成差异的随机数, 需要利用静态(static)局部变量, 这样漫衍工具和引擎就能保持(hold)状态(state), 每次都生成一个新的;

生成随机的整数, 利用漫衍工具uniform_int_distribution<>, 默认模板参数是int;

生成随机的浮点数, 利用漫衍工具uniform_real_distribution<>, 默认模板参数是double;

代码:

#include <iostream>  
#include <vector>  
#include <string>  
#include <random>  
      
      
using namespace std;  
      
std::vector<unsigned> good_randVec()  
{  
    static std::default_random_engine e; //静态  
    static std::uniform_int_distribution<unsigned> u(0,9); //静态  
    std::vector<unsigned> ret;  
    for(size_t i=0; i<10; ++i)  
        ret.push_back(u(e));  
    return ret;  
}  
      
int main()  
{  
    std::default_random_engine e;  
    std::cout << "engine : ";  
    for(size_t i=0; i<10; ++i)  
        std::cout << e() << " ";  
    std::cout << std::endl;  
      
    std::cout << "uniform : ";  
    std::uniform_int_distribution<unsigned> u(0, 9); //即[0, 9]  
    for(size_t i=0; i<10; ++i)  
        std::cout << u(e) << " ";  
    std::cout << std::endl;  
      
    std::cout << "min : " << e.min() << " max : " << e.max() << std::endl;  
      
    std::vector<unsigned> v1(good_randVec());  
    std::vector<unsigned> v2(good_randVec());  
    for(size_t i=0; i<v1.size(); ++i)  
        std::cout << v1[i] << " ";  
    std::cout << std::endl;  
    for(size_t i=0; i<v2.size(); ++i)  
        std::cout << v2[i] << " ";  
    std::cout << std::endl;  
      
    std::uniform_real_distribution<double> ud(0, 1);  
    std::cout << "float : ";  
    for(size_t i=0; i<10; ++i)  
        std::cout << ud(e) << " ";  
    std::cout << std::endl;  
      
    return 0;  
}

输出:

engine : 16807 282475249 1622650073 984943658 1144108930 470211272 101027544 1457850878 1458777923 2007237709   
uniform : 3 5 8 0 0 5 6 0 3 0   
min : 1 max : 2147483646  
0 1 7 4 5 2 0 6 6 9   
3 5 8 0 0 5 6 0 3 0   
float : 0.686773 0.930436 0.526929 0.653919 0.701191 0.762198 0.0474645 0.328234 0.75641 0.365339

作者:csdn博客 Spike_King

    关键字:

在线提交作业