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

后端 未结 7 1236
遇见更好的自我
遇见更好的自我 2020-12-05 05:34

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 wi

7条回答
  •  星月不相逢
    2020-12-05 05:38

    You should be able to do something like:

    std::default_random_engine e((unsigned int)time(0));
    int i = e();
    

    The quality of the default_random_engine is implementation dependent. You could also use std::min_rand0 or std::min_rand.

    Probably a better way to seed a random engine is with as true a random number as is available from the implementation rather than use time.

    E.g.

    std::random_device rd;
    std::default_random_engine e( rd() );
    

提交回复
热议问题