如何调用随机函数

How to call a random function

本文关键字:随机 函数 调用 何调用      更新时间:2023-10-16

假设我有一个类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;
}