When dealing with two-dimensional arrays, e.g. matrices you need to visit elements quite often. The straight forward way to do this is by two nested loops:
for( int i=0; i < n; ++i ) {
for( int j=0; j < m; ++j ) {
// do something with data[i][j]
}
}
This code principle then is often copied over and over again throughout the code. How do you solve this to become DRY? I think the only way to solve this is to use a visitor function with function pointers, right?
Edit: To be more constructive, lets assume you have matrix type typedef double** Matrix;
.
For C++ this might be solved this way: Loop over matrix elements applying variable function
First job: consider recasting data
as a struct
representing the matrix, or, failing that, a simple typedef
. I'll assume you do the former.
"// do something with data[i][j]
" could be a function (a foo
say) that takes i
, j
, and a pointer to the matrix struct
as arguments.
Then you only need one function that does the looping: that function takes the function pointer to an appropriate foo
, and the matrix struct
pointer.
Your job is then to implement the various foo
s, according to your requirements.
Don't use macros for this: they make debugging difficult, especially if they introduce hard-coded variable names like i
and j
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With