Generating random integer from a range

前端 未结 13 1515
失恋的感觉
失恋的感觉 2020-11-22 03:12

I need a function which would generate a random integer in given range (including border values). I don\'t unreasonable quality/randomness requirements, I have four requirem

13条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 04:02

    The simplest (and hence best) C++ (using the 2011 standard) answer is

    #include 
    
    std::random_device rd;     // only used once to initialise (seed) engine
    std::mt19937 rng(rd());    // random-number engine used (Mersenne-Twister in this case)
    std::uniform_int_distribution uni(min,max); // guaranteed unbiased
    
    auto random_integer = uni(rng);
    

    No need to re-invent the wheel. No need to worry about bias. No need to worry about using time as random seed.

提交回复
热议问题