How do I generate a random number using the C++11

2019-01-13 21:29发布

The new C++11 Standard has a whole chapter dedicated to random number generators. But how do I perform the simplest, most common task that used to be coded like this, but without resorting to the standard C library:

srand((unsigned int)time(0));
int i = rand();

Are there reasonable defaults for random-number engines, distributions, and seeds that one could use out of the box?

标签: c++ random c++11
7条回答
▲ chillily
2楼-- · 2019-01-13 22:04

Here you go. Random doubles in a range:

// For ints
// replace _real_ with _int_, 
// <double> with <int> and use integer constants

#include <random>
#include <iostream>
#include <ctime>
#include <algorithm>
#include <iterator>

int main()
{
    std::default_random_engine rng(std::random_device{}()); 
    std::uniform_real_distribution<double> dist(-100, 100);  //(min, max)

    //get one
    const double random_num = dist(rng);

    //or..
    //print 10 of them, for fun.
    std::generate_n( 
        std::ostream_iterator<double>(std::cout, "\n"), 
        10, 
        [&]{ return dist(rng);} ); 
    return 0;
}
查看更多
登录 后发表回答