[英]srand() + rand() with local scope
I have a function that calls srand and rand like this: 我有一个函数调用srand和rand像这样:
void foo() {
int seed = some_operation();
std::srand(seed);
int value = std::rand();
// Do something with random value
}
However, I don't want to change the global state of rand . 但是,我不想改变兰德的全局状态。 Whats the easiest way to get a random number then?
什么是获取随机数的最简单方法呢?
Requirements: 要求:
Edit: 编辑:
There is a stackoverflow question asking how to generate random numbers. 有一个stackoverflow 问题询问如何生成随机数。 The accepted answer however shows how to generate truly unique random numbers, using a slow std::random_device .
然而,接受的答案显示了如何使用慢速std :: random_device生成真正独特的随机数。 I just needed a simple generator using a fixed seed instead.
我只需要一个使用固定种子的简单生成器。
C++11 is fine
C ++ 11很好
Then use the new pseudorandom number library : 然后使用新的伪随机数库 :
#include <random>
int foo() {
int seed = some_operation();
std::minstd_rand rand(seed);
int value = rand();
// Do something with random value
}
minstd_rand
is a simple linear congruential engine, similar to that typically used by std::rand()
, but with its state encapsulated in a class. minstd_rand
是一个简单的线性同余引擎,类似于std::rand()
通常使用的引擎,但其状态封装在一个类中。 Other engines are available, if you need a higher quality pseudorandom sequence. 如果您需要更高质量的伪随机序列,则可以使用其他引擎。 The Mersenne Twister,
std::mt19937
, is usually a good choice if you don't have specific requirements. 如果您没有特殊要求,Mersenne Twister,
std::mt19937
通常是一个不错的选择。
<random>
defines a number of PRNG classes that you can use, which do not use global states. <random>
定义了许多可以使用的PRNG类,它们不使用全局状态。
For example, using a default Mersenne Twister, std::mt19937
: 例如,使用默认的Mersenne Twister,
std::mt19937
:
#include <iostream>
#include <random>
int main() {
int seed = 1234;
std::mt19937 rng(seed);
std::cout << "Random number: " << rng() << std::endl;
}
One approach is to provide your own implementation, with its own seed data. 一种方法是使用自己的种子数据提供自己的实现。 A template for doing that is provided in the manpage for rand() .
用于执行此操作的模板在rand()的联机帮助页中提供 。
static unsigned long next = 1;
/* RAND_MAX assumed to be 32767 */
int myrand(void) {
next = next * 1103515245 + 12345;
return((unsigned)(next/65536) % 32768);
}
void mysrand(unsigned seed) {
next = seed;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.