您的位置:首页 > 其它

表驱动法举例

2015-06-29 16:32 267 查看
使用表驱动法要面临的两个问题:

1. 如何访问表?可选的方式有直接访问、索引访问和阶梯访问。

2. 表中存什么?如果要得到的是数据,则将数据放进表中;如果要得到的是某个动作,则将函数指针放进表中。

例1:给定分数评出等级,保证分数范围在0-100内,规定90-100分等级为A,80-89为B,70-79为C,60-69为D,0-59为E。

函数原型为:char GetGrade(int score);

一般做法

typedef int (*AuthFunc)(const char *, const char*);

int Offset(unsigned n)
{
int offset;

for (offset = 0; n; n >>= 1, offset++);
return offset;
}

int main()
{
const static AuthFunc authFunc[] = {
NULL,
AuthByPwd,
AuthByFingerprint,
AuthByToken,
AuthByLdap,
AuthByRadius,
};
int authType, ret, idx[2] = {0};
char user[32], pass1[32], pass2[32];

while (~scanf("%d", &authType)) {
if (authType & (authType - 1)) {
scanf("%s%s%s", user, pass1, pass2);
idx[0] = Offset(authType & -authType);
authType &= authType - 1;
idx[1] = Offset(authType & -authType);
ret = (authFunc[idx[0]](user, pass1) && authFunc[idx[1]](user, pass2))
|| (authFunc[idx[0]](user, pass2) && authFunc[idx[1]](user, pass1));
} else {
scanf("%s%s", user, pass1);
idx[0] = Offset(authType & -authType);
ret = authFunc[idx[0]](user, pass1);
}
printf("auth %s\n", ret ? "success" : "fail");
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: