I have a series of NX objects (e.g., a static bool array of dimension [NX][N1][N2] in the example below).
I would like to loop over these objects. At each iteration, an object called ‘A’ is to function as a surrogate for the corresponding element ‘B[x]’ in the series.
However, the code inside the loop is legacy code, so we cannot really change how we refer to ‘A’ itself
const int NX = ...;
const int N1 = ...;
const int N2 = ...;
bool B[NX][N1][N2];
Code_needed: declare A here (maybe first defining a class template?)
int main(){
for(int x = 0; x < NX; ++x){
Code_needed: make A refer to B[x] here (maybe A = &B[x])
// In the following, "A[i][j]" should refer to B[x][i][j]...
A[3][5] = true; // This is legacy code, so we cannot change it
// (e.g., cannot add a * in front of A)
}
}
Note that the types of objects on which I want to apply this are heavy, such as arrays of containers, so copying them over inside the loop is not acceptable. Maximizing performance is generally of interest in this application.
Would appreciate the help!!
EDIT: How would the answer be affected, if A were to be a scalar (i.e., it is B[NX] only)?
You can define a reference to a two-dimensional array inside the for loop:
Now
A[i][j]is equivalent toB[x][i][j].Note that you cannot move the definition of
Aoutside the for loop, because references have to be initialized when they are defined, and they cannot be rebound later.If you need to define
Aoutside the for loop and reassign inside the for loop, use a pointer instead:And here is a complete code example which compiles just fine on my compiler:
You can also write an alias class template which overloads the assignment operator appropriately:
This works with arrays:
And plain bools: