在程序中,经常在不同的类中生成随机数。所以我想创建一个返回生成器std :: mt19937的单个实例的类。我还考虑到一些编译器不能与std :: random_device一起使用(为此,请检查熵的值)。我创建了一个类单例。
#include <iostream>
#include <random>
#include <chrono>
class RandomGenerator
{
public:
static RandomGenerator& Instance() {
static RandomGenerator s;
return s;
}
std::mt19937 get();
private:
RandomGenerator();
~RandomGenerator() {}
RandomGenerator(RandomGenerator const&) = delete;
RandomGenerator& operator= (RandomGenerator const&) = delete;
std::mt19937 mt;
};
RandomGenerator::RandomGenerator() {
std::random_device rd;
if (rd.entropy() != 0) {
mt.seed(rd());
}
else {
auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
mt.seed(seed);
}
}
std::mt19937 RandomGenerator::get() {
return mt;
}
int main() {
std::mt19937 &mt = RandomGenerator::Instance().get();
std::uniform_real_distribution<double> dist(0.0, 1.0);
for (std::size_t i = 0; i < 5; i++)
std::cout << dist(mt) << "\n";
std::cout << "\n";
std::mt19937 &mt2 = RandomGenerator::Instance().get();
std::uniform_real_distribution<double> dist2(0.0, 1.0);
for (std::size_t i = 0; i < 5; i++)
std::cout << dist2(mt2) << "\n";
return 0;
}
但是当我离开类生成器std :: mt19937时,随机数开始重复。怎么避免呢?
0.389459
0.68052
0.508421
0.0758856
0.0137491
0.389459
0.68052
0.508421
0.0758856
0.0137491
P.S。有没有比时间更好的初始化发生器的方法?
解决方案
在以下编译器下测试过:Visual Studio,MinGW,DevC ++。
#include <iostream>
#include <random>
#include <chrono>
class RandomGenerator
{
public:
static RandomGenerator& Instance() {
static RandomGenerator s;
return s;
}
std::mt19937 & get();
private:
RandomGenerator();
~RandomGenerator() {}
RandomGenerator(RandomGenerator const&) = delete;
RandomGenerator& operator= (RandomGenerator const&) = delete;
std::mt19937 mt;
};
RandomGenerator::RandomGenerator() {
std::random_device rd;
if (rd.entropy() != 0) {
mt.seed(rd());
}
else {
auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
mt.seed(seed);
}
}
std::mt19937 & RandomGenerator::get() {
return mt;
}
int main() {
std::mt19937 &mt = RandomGenerator::Instance().get();
std::uniform_real_distribution<double> dist(0.0, 1.0);
for (std::size_t i = 0; i < 5; i++)
std::cout << dist(mt) << "\n";
std::cout << "\n";
std::mt19937 &mt2 = RandomGenerator::Instance().get();
std::uniform_real_distribution<double> dist2(0.0, 1.0);
for (std::size_t i = 0; i < 5; i++)
std::cout << dist2(mt2) << "\n";
return 0;
}
答案 0 :(得分:4)
std::mt19937 get();
会返回一份副本。每次拨打get()
时,都会复制引擎的初始状态。 mt19937
是伪随机引擎,每个状态产生一个预定的序列。如果两个实例的状态相同,则它们将产生相同的序列。使函数返回一个引用,以便使用生成的每个新数字更新单例实例的状态。
std::mt19937 & RandomGenerator::get() {
return mt;
}