在C中,如何编写N维嵌套for循环,其中N是可变的

CAM*_* HG 0 c nested-loops n-dimensional

我需要写一下这句话:

for ( int i1 = i1_min; i1 < width; ++i1 )
    for ( int i2 = i2_min; i2 < i2_max; ++i2 )
        for ( int i3 = i3_min; i3 < i3_max; ++i3 )
            ...
                for ( int iN = iN_min; iN < iN_max; ++iN )
Run Code Online (Sandbox Code Playgroud)

怎么做?

Pat*_*rts 5

您可以编写递归函数loopn()来执行此操作:

void loopn_recurse (int *min, int *max, int *counters, size_t N, size_t n, void (*func)(int*, size_t)) {
  for (int i = min[n]; i < max[n]; ++i) {
    counters[n] = i;

    if (N - n > 1) {
      loopn_recurse(min, max, counters, N, n + 1, func);
    } else {
      // innermost algorithm
      func(counters, N);
    }
  }
}

void loopn (int *min, int *max, int *counters, size_t N, void (*func)(int*, size_t)) {
  assert(N > 0);
  loopn_recurse(min, max, counters, N, 0, func);
}

// example usage

void test (int *counters, size_t N) {
  for (size_t j = 0; j < N; ++j) {
    printf("%d ", counters[j]);
  }

  putchar('\n');
}

loopn((int[]){ 1, 2, 3, 4, 5 }, (int[]){ 2, 4, 6, 8, 10 }, (int[5]){}, 5, test);
Run Code Online (Sandbox Code Playgroud)

在线尝试!