Mersenne Twister 种子作为成员变量
Mersenne Twister seed as a member variable
我想知道如何将梅森随机数生成器保留为成员变量并在同一个 class.
中使用它
我写了下面的 class,它工作得很好,但我不喜欢 std::mt19937
被初始化。我想知道有没有办法在Test
的构造函数中初始化它?
#include <iostream>
#include <cmath>
#include <random>
#include <chrono>
#include <ctime>
class Test{
public:
Test()
{
}
void foo()
{
auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
}
private:
std::mt19937 rnd
{
std::chrono::high_resolution_clock::now().time_since_epoch().count()
};
}
我认为您对 class 初始化中 a 的确切作用感到困惑。当你有
struct foo
{
foo() {}
int bar = 10;
};
class 中的初始化只是
的语法糖
struct foo
{
foo() : bar(10) {}
int bar;
};
每当编译器将成员添加到成员初始值设定项列表时(这是在您忘记它或编译器提供构造函数时完成的),它都会使用您在初始化中使用的内容。所以用你的代码
class Test{
public:
Test()
{
}
void foo()
{
auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
}
private:
std::mt19937 rnd
{
std::chrono::high_resolution_clock::now().time_since_epoch().count()};
};
};
变成
class Test{
public:
Test() : rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count())
{
}
void foo()
{
auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
}
private:
std::mt19937 rnd;
};
不真正这样做的好处是你不必重复
rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count())
在您编写的每个构造函数中,但如果您需要特定构造函数的其他内容,您始终可以覆盖它。
我想知道如何将梅森随机数生成器保留为成员变量并在同一个 class.
中使用它我写了下面的 class,它工作得很好,但我不喜欢 std::mt19937
被初始化。我想知道有没有办法在Test
的构造函数中初始化它?
#include <iostream>
#include <cmath>
#include <random>
#include <chrono>
#include <ctime>
class Test{
public:
Test()
{
}
void foo()
{
auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
}
private:
std::mt19937 rnd
{
std::chrono::high_resolution_clock::now().time_since_epoch().count()
};
}
我认为您对 class 初始化中 a 的确切作用感到困惑。当你有
struct foo
{
foo() {}
int bar = 10;
};
class 中的初始化只是
的语法糖struct foo
{
foo() : bar(10) {}
int bar;
};
每当编译器将成员添加到成员初始值设定项列表时(这是在您忘记它或编译器提供构造函数时完成的),它都会使用您在初始化中使用的内容。所以用你的代码
class Test{
public:
Test()
{
}
void foo()
{
auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
}
private:
std::mt19937 rnd
{
std::chrono::high_resolution_clock::now().time_since_epoch().count()};
};
};
变成
class Test{
public:
Test() : rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count())
{
}
void foo()
{
auto randomNum = std::uniform_int_distribution<>(0, threads.size())(rnd);
}
private:
std::mt19937 rnd;
};
不真正这样做的好处是你不必重复
rnd(std::chrono::high_resolution_clock::now().time_since_epoch().count())
在您编写的每个构造函数中,但如果您需要特定构造函数的其他内容,您始终可以覆盖它。