Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to iterate over an n-dimensional array (where n is variable) without using recursion?

Is there a way to iterate over an n-dimensional array (where n is variable) without using recursion? I'm using C++ at the moment, but I guess an answer in almost any language would do.

EDIT: Actually my real question is a bit different: I actually want to enumerate the indices of the array. Simple 2D example, with a 2x2 array: 0,0; 0,1; 1,0; 1,1.

like image 524
static_rtti Avatar asked Jul 05 '11 20:07

static_rtti


1 Answers

void iterate(const std::vector<int> &dims)
{
    std::vector<int> idxs(dims.size());

    while (1)
    {
        // Print
        for (int i = 0; i < dims.size(); i++)
        {
            std::cout << idxs[i] << " ";
        }
        std::cout << "\n";

        // Update
        int j;
        for (j = 0; j < dims.size(); j++)
        {
            idxs[j]++;
            if (idxs[j] < dims[j]) break;
            idxs[j] = 0;
        }
        if (j == dims.size()) break;
    }
}
like image 122
Oliver Charlesworth Avatar answered Oct 23 '22 04:10

Oliver Charlesworth