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

Time:07-25

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

    }
}

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related