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

后端 未结 7 1229
遇见更好的自我
遇见更好的自我 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:55

    Random number generation is a difficult problem. There is no truly random way to do it. If you are just generating randomness to seed a game environment then your approach should be fine. rand() has several shortcomings.

    If you are needing randomness to generate encryption keys then you're S.O.L. The best way in that case is to go out to the operating system, which usually has mechanism. On POSIX that's random() (or read from /dev/random if you're so disposed). On Windows you can use the CryptoAPI:

    https://www.securecoding.cert.org/confluence/display/seccode/MSC30-C.+Do+not+use+the+rand%28%29+function+for+generating+pseudorandom+numbers

提交回复
热议问题