Is the library in c++11 portable?

2019-06-16 19:13发布

Is the library in c++11 portable? I have avoided rand() because I heard it wasn't portable.

标签: c++ random c++11
3条回答
霸刀☆藐视天下
2楼-- · 2019-06-16 19:25

How do you define "portable"?

If by "portable", you mean "will produce binary identical sequences of random numbers given the same input", then yes, rand isn't portable. And yes, the C++ random generators are portable (most of them. Not std::default_random_engine or std::random_device), because they implement specific algorithms. rand is allowed to be anything, as long as it's not entirely unlike a random number generator.

That being said, as @PeteBecker pointed out, the distributions themselves are not so well-defined. So while std::mt19937 will produce the same sequence of values for a given seed, different std::uniform_int_distributions can give different values for the same input sequence and range.

Of course, if you need consistency, you can always define your own distribution.

查看更多
【Aperson】
3楼-- · 2019-06-16 19:32

The random number engines described in <random> have explicit requirements for their algorithms to ensure portability. The distributions do not.

查看更多
4楼-- · 2019-06-16 19:41

You can generate "identical sequences of random numbers given the same input" (from @Nicol Bolas) with std::mt19937 (Mersenne Twister) for example. You definitely couldn't do that with rand() which was quite annoying.

Related questions:

查看更多
登录 后发表回答