C/C++中写一个函数,如何代替if else,switch,while等语句来实现 "不同值 对应调用 不同函数"?
怪我咯
怪我咯 2017-04-17 13:12:01
0
9
1114

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

怪我咯
怪我咯

走同样的路,发现不同的人生

모든 응답(9)
迷茫

让我想到多年前写的一个例程,思路和你的差不多,只不过没有使用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

大家讲道理

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

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;
    }
}
PHPzhong

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

利用&&和|| 的短路求值特性来实现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])();

伊谢尔伦

我首先想到的是goto...

Peter_Zhu

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

#include <iostream>
#include <functional>
#include <map>
using namespace std;

void fun1()
{
    cout << "fun1\n";
}
void fun2()
{
    cout << "fun2\n";
}
void fun3()
{
    cout << "fun3\n";
}
int main()
{
    map<int, function<void()>> funs;
    funs[23] = fun1;
    funs[33] = fun2;
    funs[57] = fun3;

    funs[23]();
    
    
    return 0;
}
Ty80
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)();
黄舟
result = a==1?func():a==2?func2():a==3?func3():func4();
大家讲道理

帮不到大家,已删

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!