表驱动法举例
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);
一般做法
View Code
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
相关文章推荐
- 网站301重定向解答
- python中的namespace
- oracle合并查询
- python中self.__class__
- 史上最强视频网站真实地址解析
- Swift 集合类型
- EditText的常用技巧
- 记VS2008初始化Microsoft Visual Sourcesafe源代码管理提供程序时失败
- K最邻近算法和局部敏感哈希LSH
- [华为机试练习题]12.整型字符串排序
- json学习系列(3)-JSONObject的过滤设置
- Kerberos ticket lifetime及其它
- UNP 环境配置
- php基础教程-输出Hello World
- 链表的游标实现
- linux core文件GDB调试方法
- 桥接模式多维思想
- nginx 中禁止爬虫
- 不要轻易在数据库(尤其是线上数据库)执行,update、delete数据 !!!
- 如何成为一名优秀的web前端工程师(前端攻城师)?