lundi 9 novembre 2015

Struct table. if... else if... else if... alternative

I made an "alternative" to a giant list of if.. else if.. else if..... statements:

#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;
}

Is there any other (prettier? efficient?) way of doing this without a block of if..else if statements?

I assume that this method is slightly slower than a list of if...else if statements?

Aucun commentaire:

Enregistrer un commentaire