jog*_*pan 33
这是为此目的使用C++ 11随机数生成的方法(根据http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution调整):
#include <random>
#include <iostream>
int main()
{
/* Initialise. Do this once (not for every
random number). */
std::random_device rd;
std::mt19937_64 gen(rd());
/* This is where you define the number generator for unsigned long long: */
std::uniform_int_distribution<unsigned long long> dis;
/* A few random numbers: */
for (int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
相反的unsigned long long,你可以使用std::uintmax_t从cstdint获得尽可能大的整数的范围(不使用实际的大整数库).
ken*_*ytm 12
我们可以轻松地将随机数生成器引擎包装成类似srand/rand的方法,如下所示:
#include <random>
#include <iostream>
struct MT19937 {
private:
static std::mt19937_64 rng;
public:
// This is equivalent to srand().
static void seed(uint64_t new_seed = std::mt19937_64::default_seed) {
rng.seed(new_seed);
}
// This is equivalent to rand().
static uint64_t get() {
return rng();
}
};
std::mt19937_64 MT19937::rng;
int main() {
MT19937::seed(/*put your seed here*/);
for (int i = 0; i < 10; ++ i)
std::cout << MT19937::get() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
(喜欢srand和rand,这个实现不关心线程安全.)
那么包装函数是如此微不足道,你可以直接使用引擎.
#include <random>
#include <iostream>
static std::mt19937_64 rng;
int main() {
rng.seed(/*put your seed here*/);
for (int i = 0; i < 10; ++ i)
std::cout << rng() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)