C/C++中写一个函数,如何代替if else,switch,while等语句来实现 "不同值 对应调用 不同函数"?

浏览:43日期:2023-05-25

问题描述

功能类似如下描述: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>应该可以解决,大家还有其他方法吗?

问题解答

回答1:

让我想到多年前写的一个例程,思路和你的差不多,只不过没有使用map(事实上数据量小的时候不用map性能反而好):

#include <stdio.h>#include <string.h>typedef void(*VOID_FUNC_PTR)(void);typedef struct{ char *pszInput; VOID_FUNC_PTR func;} FUNC_REG;void hello(void){ puts('I know you are saying hello.');}void hey(void){ puts('hey~hey.');}void someother(void){ puts('some more out put.');}void defaultFunc(void){ puts('there is no function for this anyway.');}FUNC_REG func_reg_list[] = { 'hello', hello, 'hey', hey, 'someother', someother};VOID_FUNC_PTR LookupFunc(char *pszInput){ int i; for (i = 0; i < sizeof(func_reg_list) / sizeof(func_reg_list[0]); i++) {if (0 == strcmp(pszInput, func_reg_list[i].pszInput)){ return func_reg_list[i].func;} } return defaultFunc;}int main(){ VOID_FUNC_PTR func = NULL; char szInput[256];while (EOF != scanf('%s', szInput)) {func = LookupFunc(szInput);if (func != NULL){ (*func)(); } } return 0;}

原文:http://blog.csdn.net/cashey1991/article/details/8333954

回答2:

想完成一个图灵完备的结构的话,你应该使用责任链模式:

class IAction{public: ~IAction(){} virtual void DoSomething(int value) = 0;};struct ActionFilterResult{ bool runTheAction; bool continueFiltering; IAction* action;};class IActionFilter{public: ~IActionFilter(){} virtual ActionFilterResult Evaluate(int value) = 0;};vector<unique_ptr<IActionFilter>> filters;void Run(int value){ for(auto& filter : filters) {auto result = filter->Evaluate(value);if (result.runTheAction) result.action->DoSomething(value);if (!result.continueFiltering) break; }}回答3:

我就说一个山寨算法吧,绝不用if,else,while....哈哈(n == 23 && func1())|| (n == 33 && fun2())|| (n == 57 && fun3())|| (n == 246 && fun4())|| (n == 132 && func5());

利用&&和|| 的短路求值特性来实现if,else

回答4:

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])();

回答5:

我首先想到的是goto...

回答6:

c++11的话,可以使用function代替函数指针;

#include <iostream>#include <functional>#include <map>using namespace std;void fun1(){ cout << 'fun1n';}void fun2(){ cout << 'fun2n';}void fun3(){ cout << 'fun3n';}int main(){ map<int, function<void()>> funs; funs[23] = fun1; funs[33] = fun2; funs[57] = fun3; funs[23](); return 0;}回答7:

void f0() { cout << 'this is function 0'; }void f1() { cout << 'this is function 1'; }void f2() { cout << 'this is function 2'; }void f3() { cout << 'this is function 3'; }void f_default() { cout << 'out of range'; }std::map<int, void(*)(void)> f = { { 12, f0 }, { 32, f1 }, { 48, f2 }, { 99, f3 },};(f.count(n) ? f[n] : f_default)();回答8:

result = a==1?func():a==2?func2():a==3?func3():func4();回答9:

帮不到大家,已删

相关文章: