Clean ways to write multiple 'for' loops

前端 未结 16 985
傲寒
傲寒 2020-12-22 15:22

For an array with multiple dimensions, we usually need to write a for loop for each of its dimensions. For example:

vector< vector< vector         


        
16条回答
  •  长情又很酷
    2020-12-22 16:00

    One thing you may want to try if you only have statements in the inner-most loop - and your concern is more about the overly verbose nature of the code - is to use a different whitespace scheme. This will only work if you can state your for loops compactly enough so that they all fit on one line.

    For your first example, I would rewrite it as:

    vector< vector< vector > > A;
    int i,j,k;
    for(k=0;k

    This is kinda pushing it because you are calling functions in the outer loops which is equivalent to putting statements in them. I have removed all unnecessary white-space and it may be passible.

    The second example is much better:

    double B[10][8][5];
    int i,j,k;
    
    for(k=0;k<10;k++) for(i=0;i<8;i++) for(j=0;j<5;j++) {
        do_something_on_B(B[k][i][j]);
    }
    

    This may be different whitespace convention than you like to use, but it achieves a compact result that nonetheless does not require any knowledge beyond C/C++ (such as macro conventions) and does not require any trickery like macros.

    If you really want a macro, you could then take this a step further with something like:

    #define FOR3(a,b,c,d,e,f,g,h,i) for(a;b;c) for(d;e;f) for(g;h;i)
    

    which would change the second example to:

    double B[10][8][5];
    int i,j,k;
    
    FOR3(k=0,k<10,k++,i=0,i<8,i++,j=0,j<5,j++) {
        do_something_on_B(B[k][i][j]);
    }
    

    and the first example fares better too:

    vector< vector< vector > > A;
    int i,j,k;
    FOR3(k=0,k

    Hopefully you can tell fairly easily which statements go with which for statements. Also, beware the commas, now you can't use them in a single clause of any of the fors.

提交回复
热议问题