當我使用 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;
}
我已經定義了一個命名空間來實作這些功能:
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;
}
}
基本上我希望能夠輕松地在模擬隨機和真正隨機之間進行切換以進行測驗。因此,在我的主代碼中,我可以將 simulatingRandom 設定為 true,然后將其更改為 false。也許有更好的方法來測驗涉及隨機的函式。如果是這樣,我愿意接受任何建議。
uj5u.com熱心網友回復:
的最后一個引數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();
}
};
然后,您可以將其稱為:
std::shuffle (v.begin(), v.end(), myRand::RandInt());
min請注意,max如果您將simulatingRandom值設定true為與預期值匹配,則需要調整 的值。如果它們與真實值不匹配,則std::shuffle可能不會像應有的那樣隨機。
必須以通常的提醒結束,不要rand在現代代碼中使用:為什么使用 rand() 被認為是不好的?特別是沒有先打電話srand。的使用是被棄用rand的主要原因。std::random_shuffle
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/529456.html
標籤:C 测试
上一篇:帶有連接節點的鏈接的聚集氣泡
