【问题标题】:Boost::multi_array loopingBoost::multi_array 循环
【发布时间】:2012-02-29 01:34:52
【问题描述】:

我查看了this post,它解决了如何使用boost::multi_array::origin() 函数对非从零开始的数组进行循环,但这只会创建一个循环。

如何遍历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>;
      }
   }
}

当给定一个上下界都未知的数组时?

【问题讨论】:

    标签: c++ boost boost-multi-array


    【解决方案1】:

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

    【讨论】:

    • 但这要求你在写代码的时候就知道数组的维度,失去了multi_array的大部分通用性。
    • @DavidDoria,在A(extents[2][range(1,4)][range(-1,3)]) 中,您可以将硬编码的维度值替换为您喜欢的任何值,无论是从磁盘加载的值还是用户输入的值。为了简化示例,我对数字进行了硬编码。
    • 重新排列的示例以更好地说明如何在数组初始化位置之外查询维度范围。
    • 但是您仍然列出 iMin、jMin、kMin... 如果 printArray 不知道 array_type 是 3D 怎么办?
    猜你喜欢
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2011-07-31
    • 2020-03-07
    相关资源
    最近更新 更多