Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid repeating myself in nested loops

Tags:

c++

I have a method with nested loops like below inside which I do some computationally expensive stuff and some computationally cheap stuff:

for(int i = 0; i < SIZE_I; ++i) {
    // Do cheap stuff 1
    // Do computationally expensive stuff 1
    for(int j = 0; j < SIZE_J; ++j) {
        // Do cheap stuff 2
        // Do computationally expensive stuff 2
        for(int k = 0; k < SIZE_K; ++k) {
            // Do cheap stuff 3
            // Do computationally expensive stuff 3
        }
    }
}

Currently, I call my method once. But I need to separate my cheap stuff from my expensive stuff. The problem is that if I develop two methods, I will need to repeat the nested loops and lots of code tangled with them.

I wonder if there is a best practice or tool to help me break my single method into two methods without repeating a whole lot of code. Or maybe if there is a solution to separate the cheap from the expensive without the need to break down my single method into two methods?

like image 254
user3405291 Avatar asked Feb 23 '26 05:02

user3405291


1 Answers

I ended up doing this:

enum CallStatus {
    CallStatus_Cheap = 0,
    CallStatus_Expensive
};

bool MyClass::MyMethod(MyClass::CallStatus callStatus)
{
    for(int i = 0; i < SIZE_I; ++i) {

        switch (callStatus) {
        case MyClass::CallStatus_Cheap:
            // Do cheap stuff 1
            break;
        case MyClass::CallStatus_Expensive:
            // Do computationally expensive stuff 1
            break;
        default:
            break;
        }

        for(int j = 0; j < SIZE_J; ++j) {

            switch (callStatus) {
            case MyClass::CallStatus_Cheap:
                // Do cheap stuff 2
                break;
            case MyClass::CallStatus_Expensive:
                // Do computationally expensive stuff 2
                break;
            default:
                break;
            }

            for(int k = 0; k < SIZE_K; ++k) {

                switch (callStatus) {
                case MyClass::CallStatus_Cheap:
                    // Do cheap stuff 3
                    break;
                case MyClass::CallStatus_Expensive:
                    // Do computationally expensive stuff 3
                    break;
                default:
                    break;
                }

            }
        }
    }

// ...

}

Making use of enum as argument/parameter and switch, now I'm able to do cheap and expensive stuff separately, even though they are very entangled in nested loops.

like image 142
user3405291 Avatar answered Feb 24 '26 19:02

user3405291



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!