功能类似如下描述:
if n==23 , 调用void fun1(void);
if n==33 , 调用void fun2(void );
if n==57 , 调用void fun3(void );
if n==246 , 调用void fun4(void );
if n==132 , 调用void fun5(void );
待实现如下函数:(5个fun函数已知,n 一定为{23,33,57,246,132}中的一个)
void Test(int n)
{
...
}
我想到了map<int,pFun>应该可以解决,大家还有其他方法吗?
Reminds me of a routine I wrote many years ago. The idea is similar to yours, except that map is not used (in fact, when the amount of data is small, the performance of not using map is better):
Original text: http://blog.csdn.net/cashey1991/article/details/8333954
If you want to complete a Turing-complete structure, you should use the chain of responsibility pattern:
I’ll just talk about a copycat algorithm, never use if, else, while.... Haha
(n == 23 && func1())
|| (n == 33 && fun2() )
|| (n == 57 && fun3())
|| (n == 246 && fun4())
|| (n == 132 && func5());
Use the short-circuit evaluation characteristics of && and || to implement if,else
typedef void (*pfunc)(void);
pfunc arrfunc[16];
arrfunc[1]=func1;
arrfunc[2]=func2;
arrfunc[3]=func3;
arrfunc[8]=func5;
arrfunc[15]=func4;
(arrfunc[n/16])();
The first thing I thought of was goto...
For c++11, you can use function instead of function pointer;
Can’t help anyone, deleted