简体   繁体   中英

How can I simplify the function with two loops, or is it better to leave it as it is?

I have two almost identical functions where two loops are the same, but the code inside is different, how can I do it more correctly Leave it as it is or change both functions to one or how you do when faced with such code, just wondering which method do you think is correct.

    template <class T1>
    void function_A(T1 & array_test) {
        for (int h = 0; h < 3; ++h) {
            for (int i = 0; i < 7; ++i) {

                // CODE 1
            }
        }
    }

    template <class T1>
    void function_B(T1 & array_test) {
        for (int h = 0; h < 3; ++h) {
            for (int i = 0; i < 7; ++i) {

                // CODE 2
            }
        }
    }


if (functiontest == 0) {
    function_A(array_test);
}
if (functiontest == 1) {
    function_B(array_test);
}

I'm thinking of doing this, but I'm not sure if it's better than the top option, but inside the function there will be only code without loops, but you will also need to pass three arguments and not one

for (int h = 0; h < 3; ++h) {
    for (int i = 0; i < 7; ++i) {

        if (functiontest == 0) {
            function_A(h, i, array_test);
        }
        if (functiontest == 1) {
            function_B(h, i, array_test);
        }

    }
}

Example (without template, to better show the underlying principle). You can pass the code to test as a std::function.

#include <functional>
#include <vector>

void Test(std::function<void(int,int, std::vector<int>&)> fn, std::vector<int>& array_test)
{
    for (int h = 0; h < 3; ++h) {
        for (int i = 0; i < 7; ++i) {
            fn(h, i,array_test);
        }
    }
}

void code_1(int h, int i, std::vector<int>& array_test)
{
}


void code_2(int h, int i, std::vector<int>& array_test)
{
}

int main()
{
    std::vector<int> values{ 1,2,3 };
    Test(code_1, values);
    Test(code_2, values);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM