danijar danijar - 1 year ago 78
C++ Question

How to iterate over n dimensions?

How can I iterate over a n-dimensional array in C++ given the number of dimensions and the size of each as variables?

int n;
int size[n];

Since the number of dimensions is not fixed, I cannot write a nested loop for each dimension. I need the code to work with each number of dimensions.

In addition, it doesn't matter weather the actual data is stored in a n-dimensional array or a flat array containing all the data in a large row. Both are acceptable.

int data[16][42][14]; // n-dimensional array
int data[16 * 42 * 14]; // flat array containing the same data

Answer Source

You could use recursion, for each dimension "guess" its index and recursively invoke on a smaller problem, something along the lines of (peudo code):

   if (d >= n): //stop clause
       print res
   for each i from 0 to size[d]:
       res.append(i) //append the "guess" for this dimension
       res.removeLast //clean up environment before next iteration


  • d is the currently visited dimension
  • size,n is the input
  • res is a vector representing the current partial result

invoke with iterate(0,n,size,res), where res is initialized to an empty list.

C++ code should be something like:

void iterate(int d,int n,int size[], int res[]) {
    if (d >= n) { //stop clause
   for (int i = 0; i < size[d]; i++) { 
       res[d] = i;

full code and a simple example are available on ideone

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download