srand() + rand() 具有本地作用域 [英] srand() + rand() with local scope

查看:48
本文介绍了srand() + rand() 具有本地作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数可以像这样调用 srandrand:

I have a function that calls srand and rand like this:

void foo() {
   int seed = some_operation();
   std::srand(seed);
   int value = std::rand();
   // Do something with random value
}

然而,我不想改变 rand 的全局状态.那么获得随机数的最简单方法是什么?

However, I don't want to change the global state of rand. Whats the easiest way to get a random number then?

要求:

  • 随机数必须是基于种子的确定性
  • C++11 没问题
  • foo 应该是线程安全的
  • 不应修改 rand 的全局状态

有一个 stackoverflow 问题询问如何生成随机数.接受的答案展示了如何使用缓慢的std::random_device.我只需要一个使用固定种子的简单生成器.

There is a stackoverflow question asking how to generate random numbers. The accepted answer however shows how to generate truly unique random numbers, using a slow std::random_device. I just needed a simple generator using a fixed seed instead.

推荐答案

C++11 没问题

C++11 is fine

然后使用新的伪随机数库:

#include <random>

int foo() {
    int seed = some_operation();
    std::minstd_rand rand(seed);
    int value = rand();
    // Do something with random value
}

minstd_rand 是一个简单的线性同余引擎,类似于 std::rand() 通常使用的引擎,但其状态封装在一个类中.如果您需要更高质量的伪随机序列,则可以使用其他引擎.如果您没有特定要求,Mersenne Twister std::mt19937 通常是一个不错的选择.

minstd_rand is a simple linear congruential engine, similar to that typically used by std::rand(), but with its state encapsulated in a class. 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.

这篇关于srand() + rand() 具有本地作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆