I want to write a generic function in c++ to flatten any multidimensional vector provided. The signature of the method is as follows:
template <class U, class T>
void flatten(U* out, T& inp, int* dims, int n){
// out is the flattened output
// inp is some multidimensional vector<vector...<U>>
// dims is an array of the dimensions of inp
// n is the number of dimensions of inp
int ticker[n];
int prodLimit = 1;
int prod = 0;
// calculate prodLimit as product of elements in dims and initialize ticker
for (int i=0; i<n; i++){
ticker[i] = 0;
prodLimit *= dims[i];
}
while (prod < prodLimit){
// access the current element in inp
{...}
// update ticker
for (int i=n-1; i>0; i++){
if (ticker[i] == dims[i]){
ticker[i] == 0;
ticker[i-1] += 1;
}
}
prod += 1;
out[prod] = correctElementIn_inp;
}
}
Most of the operations are straight forward except accessing the specific component of multi-dimensional vector inp
. As the dimensions are unknown a-priori I create an array of size n
in a while loop to handle the counter for each dimension and update it properly. Now the only problem remaining is using the ticker to access the correct element in the vector.
As an example lets say the following holds:
#include <vector>
typedef std::vector<std::vector<double>> vec2;
typedef std::vector<std::vector<std::vector<double>>> vec3;
int main(){
vec2 inp1 = {...};
vec3 inp2 = {...};
int s1[2] = {2,3};
int s2[3] = {2,3,4};
...
}
Now this method should be able to handle both of inp1
and inp2
.
Is there a way of recursively accessing the vector elements without explicitly using the vector element access operator for each case.