I often find my self writing these pieces of code, specifically when I have to do something in a 2D array.
The loops are the same, except the operations inside are different and, most importantly, the operation in the last group depends on the first.
My main concern is: is there a more efficient code for large values of n,m?
for ( int y = 0 ; y < m ; ++y ) {
for ( int x = 0 ; x < n ; ++x ) {
if ( v[x][y] == z ) a = true;
}
}
for ( int y = 0 ; y < m ; ++y ) {
for ( int x = 0 ; x < n ; ++x ) {
if ( a == true ) do_something( v[x][y] );
}
}
Thanks in advance
In the general case as you describe it, the answer is probably “no” – you imply that the operation of the second look relies on the first loop being completed, so you have to do just that.
However, in the specific case you’ve listed, there are two easy optimisations:
ais settruethere’s no need to loop any further.if ( a == true )outside of the second loop, so that it’s only evaluated once and you skip the entire loop if it’s false.