Nov 20, 2013

[C++][C++11][C++14][NOTE] random generator in C++

Constructing Engine needs time. Don't construct it too often.
Member functions of distributions isn't const mem funcion.
Which is _not_ thread safe. Be aware of using it.


 
#include <random>
std::random_device // Non-deterministic , will block.
std::mt19937 // Engine, construct/copy is not fast.
std::mt19937_64 // function call ops are not const, _not_ thread safe.
std::uniform_int_distribution //function call ops are not const, _not_ thread safe.
std::shuffle // use it, _not_ random_shuffle

When is it safe to skip using uniform_int_distribution?
mt19937's [0, 2^32) -> [0, 2^N) , just using bit mask to do it.
No need to call uniform_int_distribution.

sample code:
 
#include <random>

int main()
{
   std::mt19937 mt(1234);
   std::uniform_int_distribution<int> dist(0,99);

   for (int i = 0; i < 20; ++i)
   {
      dist(mt);
   }

   return 0;
}

Reference:
rand() Considered Harmful

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.