Here is my problem, I am dealing with a n-dimensional data. Let's say n=2 for simplicity. Also I have an algorithm for 1D data. In order to extend this algorithm for 2D problem, I can do
for each row
apply algorithm
However, if I want to apply this algorithm for each column, I need to write a new function
for each column
apply algorithm
For example, assume i have a function:
void func(vector<T> &vec);
Then to apply this function to a vector I can simply call this function:
vector<T> vec;
func(vec);
For a 3D data:
T multiArray[l][m][n];
From my knowledge, if I want to apply above function for all vectors in first dimension, I will do:
for(int j=0;j<m;j++){
for(int k=0;k<n;k++){
vector<T> singleArray;
for(int i=0;i<l;i++){
singleArray.push_back(multiArray[i][j][k]);
}
func(singleArray);
}
}
However, for the same data, if I want to apply the above function for all vectors in the third dimension, I need to rewrite it as:
for(int i=0;i<l;i++){
for(int j=0;j<m;j++){
vector<T> singleArray;
for(int k=0;k<n;k++){
singleArray.push_back(multiArray[i][j][k]);
}
func(singleArray);
}
}
Basically, everything is the same except iterators in each for loop. I hope there are some ways that I can realize those two computation with one function.
Thx
I don't know a general solution but you can solve your specific problem (use the first, or the second or the third index or...) using a reference.
In the 3D case, first you can declare the loop variables (
i
,j
andk
)Next you can "link" another variable (
r
) toi
,j
ork
according to a template valueI
The following is a compilable example
--- EDIT ---
The OP ask
No.
Not this function.
But I propose a completely different (and more complex) solution. I write it but don't ask me to check if it really works.
The idea isn't based on reference anymore but on template specialization.
This time the template index is 1-based: use template value
1
if you want intercept the first index (exx
),2
if you want intercept the second index (exy
), etc.So you call
for a 1D vector,
for a 2D vector, etc.
If you call
where
I
is bigger than the dimension ofdata
, you get a compilation error.If you call
you get a compilation error but only if you compile C++11 or newer (with C++98
r
become zero; but you can add anassert()
to get a runtime error).The example