whiteiden97 whiteiden97 - 4 years ago 83
C++ Question

Create a recursive for statement in c++

I'd like to know if it is actually possible to create / define an homemade

for
statement in C++. Something similar already have been asked here:

"How to create a for loop like command in C++? #user9282's answer"

What I ask for is if we can make a
for
that performs as much
for
as we want (n times).

As example, here is a basic for-loop statement :

for (int i = 0; i < 10; i++) { ... }


I'm wondering if the new for-loop could result more like this :

int x = 20; // individual loops
int y = 3; // = amount of for-loops performed (in this case, 3)

// maybe some code generating for-loops here or something...

// result:
for (int i = 0; i < x; i++)
{
for (int j = 0; j < x; j++)
{
for (int k = 0; k < x; k++)
{
// if "y" was equal to 5, there would be 2 more for-loops here
instructions; // we can use "i", "j", "k", ... here
}
}
}


Do you think this could be possible in c++ ?

[EDIT: made clearer the code above]

In one sentence: I want to create a statement (e.g. if, while, for, switch) that puts for-loops into for-loops (just like the code above has for-loops into for-loops) so we can access multiple increments (i, j, k, ...) in the same scope.

Answer Source

If you have n nested for loops with the same bound x, you are performing xn iterations. In that case, you can just use a single index and convert it into multiple indices for convenience. For n = 2, for example:

for (int z = 0; z < x * x; ++z) {
  const int i = z / x;
  const int j = z % x;
  // ...
}

For n = 3:

for (int z = 0; z < x * x * x; ++z) {
  // The last "% x" in this line is for illustration only.
  const int i = (z / x / x) % x;
  const int j = (z / x) % x;
  const int k = z % x;
  // ...
}

i, j, k, etc. are the digits of the current iteration number z converted to base x. You could generalise this into a recursive function, or one that unpacks the digits into a vector.

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