【发布时间】:2015-11-09 20:07:55
【问题描述】:
我对 if.. else if.. else if..... 语句的巨大列表做了一个“替代”:
#include <iostream>
void test_func_ref();
struct transition_table
{
char trans_key_1;
char trans_key_2;
void(&func_ref)();
};
int main() {
transition_table test_table[] = {
{ 'A','B', test_func_ref },
{ 'B','Q', test_func_ref },
{ 'D','S', test_func_ref },
{ 'E','Q', test_func_ref },
{ 'B','W', test_func_ref },
{ 'F','Q', test_func_ref },
{ 'B','S', test_func_ref },
{ 'S','Q', test_func_ref },
{ 'B','X', test_func_ref },
{ 'R','R', test_func_ref },
{ 'B','O', test_func_ref },
{ 'K','Q', test_func_ref },
{ 'J','I', test_func_ref }
};
char choice1,choice2;
std::cin >> choice1 >> choice2;
for (int i = 0; i < (sizeof(test_table) / sizeof(test_table[0])); i++) {
if (choice1 == test_table[i].trans_key_1)
if (choice2 == test_table[i].trans_key_2) {
//Code here
std::cout << std::endl;
std::cout << "This is equal to table row " << i << std::endl;
test_table[i].func_ref();
}
}
system("pause");
return 0;
}
void test_func_ref() {
std::cout << "Voided function called" << std::endl;
}
如果没有 if..else if 语句块,还有其他(更漂亮?更高效?)的方法吗?
我认为这种方法比 if...else if 语句列表稍慢?
【问题讨论】:
-
您是否搜索过诸如“表驱动状态机”之类的内容?这似乎至少与您在这里所拥有的非常接近。
-
std::map代替 C 风格的数组会快一点 -
另一种选择是创建一个宏,该宏将为每个可能的字符输入对生成一个唯一整数,并将其用作
switch语句的索引 -
如果你的transition_table是按字母顺序排列的,你可以使用二分查找,可能会快一点。
-
您可以使用
#define CASE(x,y) (((x)<<8)|((y)<<0))代替这两个if语句使用:if (CASE(test_table[i].trans_key_1,test_table[i].trans_key_2)==CASE(choice1,choice2))。
标签: c++ performance if-statement