如何调用随机函数
How to call a random function
假设我有一个类A
,其中包含方法functionA()
,functionB()
和functionC()
:
class A {
int functionA () {
}
int functionB() {
}
int functionC() {
}
};
我将如何随机调用函数 A、函数 B 和函数 C?
方法 1
朴素的方法之一是生成一个随机数,并根据if
语句或switch
中生成的数字调用函数。
#include<iostream>
#include<time.h>
using namespace std;
int main(void)
{
A a;
srand(time(0));
int a = rand()%3;
switch (a)
{
case 0:
a.functionA();
break;
case 1:
a.functionB();
break;
case 2:
a.functionC();
break;
default:
break;
}
return 0;
}
方法 2
根据@Remy Lebeau的评论,我推荐以下方法
int main(void)
{
srand(time(0));
int (A::*arr[])() = {&A::functionA, &A::functionB, &A:functionC};
/*
**Note**
You need to call the non-static class methods using an Object of the
class. So we make an object and call methods using that object.
*/
A a;
(a.*arr[rand() % 3])();
return 0;
}
编辑
正如@cdihowie所建议的,不建议使用 c/c++ 随机库,因为生成的随机数可能不统一。我们可以使用 uniform_distribution 来生成统一的伪随机数。因此,您的最终代码如下所示:
#include <iostream>
#include <random>
#include <time.h>
using namespace std;
class A
{
public:
int functionA()
{
printf("inside functionA()n");
return 0;
}
int functionB()
{
printf("inside functionB()n");
return 0;
}
int functionC()
{
printf("inside functionC()n");
return 0;
}
};
int main(void)
{
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::uniform_int_distribution<int> distribution(0, 2);
A a;
A *aPtr = new A();
int (A::*arr[])() = {&A::functionA, &A::functionB, &A::functionC};
for (int i = 0; i < 99; i++)
{
int num = distribution(generator);
(a.*arr[num])();
}
return 0;
}
只需使用rand()
函数将其随机化,如下所示。
A a;
int randFuncIdx = std::rand() % 3;
switch(randFuncIdx) {
case 0:
a.functionA();
break;
case 1:
a.functionB();
break;
case 2:
a.functionC();
break;
default:
break;
}
相关文章:
- 循环中的随机函数
- 如何调用随机函数
- 如何在 C++ 中获取随机函数的周期性
- C++ Arduino - 随机函数不起作用
- 随机函数在循环中调用时返回相同的数字!C++
- C++随机函数给出的相同整数是输出的两倍
- C++编写随机函数和参数
- 在另一个函数中调用随机函数
- 如何在另一种语言的随机函数中复制C++兰特?
- C++中的随机函数
- 在RFC3711(SRTP)中,OpenSSL AES_ctr128_encrypt()作为密钥派生的伪随机函数意外输出
- 值噪声随机函数奇异输出
- 每次在 c++ 中调用的随机函数
- 是否有一个随机函数可以生成 0 到 1 之间的数字
- 调用随机函数 (C++)
- 具有内部随机函数的结构的CUDA移植
- 以给定概率生成1或0的随机函数
- 随机函数在c++和Matlab中
- 实现自己的随机函数是否被普遍接受?(c++)
- C++从随机函数中移除元素