当我使用 myRand::RandInt 而不是 default_random_engine 之类的东西时,出现错误。但我不明白我应该如何实现 random_engine 函数。我所做的与 std::random_shuffle 配合得很好,但我知道这个函数已被弃用,而 std::shuffle 是首选。
我正在努力让它发挥作用:
int main()
{
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::shuffle (v.begin(), v.end(), myRand::RandInt);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我定义了一个命名空间来实现这些功能:
namespace myRand {
bool simulatingRandom = false;
std::vector<int> secuenciaPseudoRandom = {1,0,1,0};
long unsigned int index = 0;
int Rand() {
//check
if (index > secuenciaPseudoRandom.size() - 1 ) {
index = 0;
std::cout << "Warning: myRand resetting secuence" << std::endl;
};
if (simulatingRandom) {
//std::cout << "myRand returning " << secuenciaPseudoRandom[i] << std::endl;
return secuenciaPseudoRandom[index++];
}
else {
return rand();
}
}
// works as rand() % i in the case of simulatingRandom == false
int RandInt(int i) {
return Rand() %i;
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,我希望能够轻松地在模拟随机和真实随机之间进行更改以进行测试。这样,在我的主代码中,我可以将 simulateRandom 设置为 true 进行测试,然后将其更改为 false。也许有更好的方法来测试涉及随机的函数。如果是这样,我愿意接受任何建议。
最后一个参数std::shuffle必须满足 的要求UniformRandomBitGenerator。生成器应该是一个对象而不是函数。例如,最小的实现是:
struct RandInt
{
using result_type = int;
static constexpr result_type min()
{
return 0;
}
static constexpr result_type max()
{
return RAND_MAX;
}
result_type operator()()
{
return Rand();
}
};
Run Code Online (Sandbox Code Playgroud)
然后您可以将其称为:
std::shuffle (v.begin(), v.end(), myRand::RandInt());
Run Code Online (Sandbox Code Playgroud)
请注意,如果您将值设置为与预期值匹配,则需要调整min和 的值。如果它们与真实值不匹配,则可能不会像应有的那样随机。maxsimulatingRandomtruestd::shuffle
必须以通常的提醒结束,不要rand在现代代码中使用:为什么使用 rand() 被认为是不好的?尤其是在没有srand先打电话的情况下。使用rand是被弃用的主要原因std::random_shuffle。
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |