gpt4 book ai didi

c++ - 结构表。如果...否则如果...否则如果...替代

转载 作者:太空宇宙 更新时间:2023-11-04 13:25:11 25 4
gpt4 key购买 nike

我对一个巨大的 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 语句 block 的情况下执行此操作?

我假设此方法比 if...else if 语句列表稍慢?

最佳答案

由于您像查找表一样使用列表来查找匹配一对的唯一值,因此您可以使用 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' << 8 | 'B'表达式提供了将两个字符组合成一个 int 的技巧通过移动第一个键 char进入 int 的高 8 位, 和 OR-ing 第二个 char进入低 8 位。

请注意,查找不再需要代码中的显式循环,因为 tbl.find(a << 8 | b) call 为您搜索。

Demo.

关于c++ - 结构表。如果...否则如果...否则如果...替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com