uniform_int_distribution的变化范围 [英] Vary range of uniform_int_distribution

查看:1558
本文介绍了uniform_int_distribution的变化范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个Random对象:

So i have a Random object:

typedef unsigned int uint32;

class Random {
public:
    Random() = default;
    Random(std::mt19937::result_type seed) : eng(seed) {}

private:
    uint32 DrawNumber();
    std::mt19937 eng{std::random_device{}()};
    std::uniform_int_distribution<uint32> uniform_dist{0, UINT32_MAX};
};

uint32 Random::DrawNumber()
{
    return uniform_dist(eng);
}

我可以通过另一个功能

推荐答案

分发对象是轻量级的。当需要一个随机数时,只需构造一个新的分布。我在游戏引擎中使用这种方法,并且在基准化之后,它可以与使用好的旧 rand()相比。

Distribution objects are lightweight. Simply construct a new distribution when you need a random number. I use this approach in a game engine, and, after benchmarking, it's comparable to using good old rand().

此外,我已经询问了如何在GoingNative 2013直播流中改变分发范围,标准委员会成员Stephen T. Lavavej建议简单地创建新的分发,因为它不应该是性能问题。

Also, I've asked how to vary the range of distribution on GoingNative 2013 live stream, and Stephen T. Lavavej, a member of the standard committee, suggested to simply create new distributions, as it shouldn't be a performance issue.

以下是我编写代码的方法:

Here's how I would write your code:

using uint32 = unsigned int;

class Random {
public:
    Random() = default;
    Random(std::mt19937::result_type seed) : eng(seed) {}
    uint32 DrawNumber(uint32 min, uint32 max);

private:        
    std::mt19937 eng{std::random_device{}()};
};

uint32 Random::DrawNumber(uint32 min, uint32 max)
{
    return std::uniform_int_distribution<uint32>{min, max}(eng);
}

这篇关于uniform_int_distribution的变化范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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