在下面的示例中,使用5个循环,我能够获得每个单独的索引以访问多维数组。对于动态系统,如果我不知道数组的维数,有没有办法实现递归函数来访问数组。=>递归地实现for循环。
例如:index[3] = 0; //=> because it is 3 dimenional all are zero
void recursiveIndexWalk(int i){
a[0] = i;
recursiveIndexWalk(a[1]);
//on the inner last recursive call a[index[0]][index[1]][index[2]] = val;
}
main(){
//my goal is to perform instead of 3 for loops => only one recursive() called
recursive(a[0]);
}
unsigned int dimensions = 3; //known
unsigned int dimension_length = { 1, 2, 3}; //known
int a[1][2][3];
int counter = 0;
for (size_t r = 0; r < 1; r++) //|
for (size_t q = 0; q < 2; q++) //|
for (size_t p = 0; p < 4; p++) //| =>recursiveForCall(indexArray)
a[i][j][k] = counter++;
例如,您可以创建一个包含所有索引id的向量,因此在每次递归中,您都可以在调用递归函数之前将索引添加到列表中,然后将其从列表中删除。
然而,在这里放弃递归的想法,而只是使用迭代技术来查看所有的排列可能是一个更好的主意。下面是一个任意的概念证明,它应该会给你一些想法:
#include <stdio.h>
const unsigned int dimensions = 3;
const unsigned int dimension_size[dimensions] = { 2, 4, 3 };
// Get first permutation.
inline void get_first_permutation( unsigned int * const permutation )
{
for ( int i = 0; i < dimensions; ++i )
permutation[i] = 0;
}
// Returns false when there are no more permutations.
inline bool next_permutation( unsigned int * const permutation )
{
int on_index = dimensions - 1;
while ( on_index >= 0 )
{
if ( permutation[on_index] >= dimension_size[on_index] )
{
permutation[on_index] = 0;
--on_index;
}
else
{
++permutation[on_index];
return true;
}
}
return false;
}
// Print out a permutation.
void print_permutation( const unsigned int * const permutation )
{
printf( "[" );
for ( int i = 0; i < dimensions; ++i )
printf( "%4d", permutation[i] );
printf( "]n" );
}
int main( int argc, char ** argv )
{
// Get first permutation.
unsigned int permutation[dimensions];
get_first_permutation( permutation );
// Print all permutations.
bool more_permutations = true;
while ( more_permutations )
{
print_permutation( permutation );
more_permutations = next_permutation( permutation );
}
return 0;
}
当然,这是假设您确实需要知道索引。如果你想更新所有计数器你可以从索引0循环到索引dim_0*dim_1*...*dim_n
/* Defined somewhere. Don't know how this gets allocated but what-evs. :) */
unsigned int dimensions = 5;
unsigned int dimension_length = { 1, 2, 4, 7, 6 };
int * int_array = ...
/* Your loop code. */
unsigned int array_length = 0;
for ( unsigned int d = 0; d < dimensions; ++d )
array_length += dimension_length[d];
int *array_pointer = int_array;
for ( unsigned int i = 0; i < array_length; ++i, ++array_pointer )
array_pointer = counter++;
如果在遍历数组时不需要索引,则可以将其视为简单数组。使用上面的已知大小的例子:
int * ap = ****a;
int n = 1 * 2 * 3 * 1 * 5;
for (size_t i = 0; i < n; ++i)
*ap++ = counter++;
我不确定递归实现能给你带来什么。如果数组太大,可能会破坏堆栈