2012-02-07 63 views
4

我看过this post,它解决了如何循环使用boost::multi_array::origin()函数而不是基于零的数组,但只创建单个循环。Boost :: multi_array looping

一个人如何遍历multi_array的每个维度,例如:

for(index i = <origin of dim 1>; ...) { 
    for(index j = <origin of dim 2>; ...) { 
     for(index k = <origin of dim 3>; ...) { 
     myArray[i][j][k] = <something>; 
     } 
    } 
} 

给出的阵列,其中上和下边界是未知的时?

回答

5

index_bases成员函数返回一个包含每个维度的索引基的容器。成员函数shape返回一个包含每个维度的范围(大小)的容器。您可以使用这两种判断指数的范围为每个维度:

typedef boost::multi_array<int, 3> array_type; 

void printArray(const array_type& a) 
{ 
    // Query extents of each array dimension 
    index iMin = a.index_bases()[0]; 
    index iMax = iMin + a.shape()[0] - 1; 
    index jMin = a.index_bases()[1]; 
    index jMax = jMin + a.shape()[1] - 1; 
    index kMin = a.index_bases()[2]; 
    index kMax = kMin + a.shape()[2] - 1; 

    for (index i=iMin; i<=iMax; ++i) 
    { 
     for (index j=jMin; j<=jMax; ++j) 
     { 
      for (index k=kMin; k<=kMax; ++k) 
      { 
       std::cout << a[i][j][k] << " "; 
      } 
     } 
    } 
} 

int main() 
{ 
    typedef array_type::extent_range range; 
    typedef array_type::index index; 
    array_type::extent_gen extents; 

    // Extents are hard-coded here, but can come from user/disk. 
    array_type a(extents[2][range(1,4)][range(-1,3)]); 

    // Populate array with values... 

    // Pass the array to a function. The function will query 
    // the extents of the given array. 
    print(a); 

    return 0; 
} 
+1

但这要求你知道你正在编写代码的时间数组的大小,失去了大部分的multi_array的泛型。 – 2016-04-07 19:29:52

+0

@DavidDoria,在'A(extents [2] [range(1,4)] [range(-1,3)])'中,你可以用你喜欢的任何东西替换硬编码的维度值,来自磁盘或来自用户的输入。为了简化示例,我对数字进行了硬编码。 – 2016-04-07 20:09:37

+0

重新排列示例以更好地说明如何在数组初始化之后查询维度范围。 – 2016-04-07 20:21:38

相关问题