【问题标题】:Struct table. if... else if... else if... alternative结构表。如果... 否则 如果... 否则 如果... 替代
【发布时间】: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)&lt;&lt;8)|((y)&lt;&lt;0)) 代替这两个if 语句使用:if (CASE(test_table[i].trans_key_1,test_table[i].trans_key_2)==CASE(choice1,choice2))

标签: c++ performance if-statement


【解决方案1】:

由于您像查找表一样使用列表来查找匹配一对的唯一值,因此您可以改用std::map

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

void test_func(char, char);

typedef void(&func_ref)(char, char);

static map<int,func_ref> tbl = {
    { 'A' << 8 | 'B', test_func },
    { 'B' << 8 | 'Q', test_func },
    { 'D' << 8 | 'S', test_func },
    ...
    { 'K' << 8 | 'Q', test_func },
    { 'J' << 8 | 'I', test_func }
};

int main() {
    char a, b;
    while (cin >> a >> b) {
        auto fp = tbl.find(a << 8 | b);
        if (fp != tbl.end()) {
            fp->second(a, b);
        }
    }
    return 0;
}

void test_func(char a, char b) {
    std::cout << "Voided function called: " << a << ":" << b << std::endl;
}

'A' &lt;&lt; 8 | 'B' 表达式提供了一种将两个字符组合成一个 int 键的技巧,方法是将第一个 char 移动到 int 的高 8 位,并将第二个 char 与低 8 位。

请注意,查找不再需要代码中的显式循环,因为 tbl.find(a &lt;&lt; 8 | b) 调用会为您进行搜索。

Demo.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 2015-12-01
    • 1970-01-01
    相关资源
    最近更新 更多