問題描述
所以我有一個隨機對象:
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);
}
我可以改變(通過另一個函數或其他方式)分布上限的最佳方法是什么?
What's the best way I can vary (through another function or otherwise) the upper bound of of the distribution?
(也愿意接受其他風格問題的建議)
(also willing to take advice on other style issues)
推薦答案
分發對象是輕量級的.當您需要隨機數時,只需構建一個新的分布.我在游戲引擎中使用這種方法,經過基準測試后,它可以與使用舊的 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的范圍的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!