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.
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;
}
}
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