开发者

Getting a byte of randomness [duplicate]

开发者 https://www.devze.com 2023-03-21 03:43 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: What is the most random function in C++?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What is the most random function in C++?

In C++, is this safe:

int main() {
srand(time(0));
unsigned char arr[10];
for(int i=0; i <sizeof(arr); ++i)
    arr[i] = (unsigned char)rand();
}

Is there a better way to randomly fill a byte array in a platform independent way? failing that, is there a better 开发者_运维知识库way to do this on windows? (I know rand() isn't a very good PRNG, I'm just using it as an example).

Thank you!


What about using boost.random? The generators it uses can be passed to std::generate to fill your array, it's platform independent and headers-only. I would give a code sample but have no boost install available at the moment.

Edit: as mentioned: in C++0x (the upcoming standard), you can use tr1::random, which is essentially just the boost library becoming part of the standard C++ library.

0

精彩评论

暂无评论...
验证码 换一张
取 消