4

関数を使用してゼロベースではない配列をループする方法を取り上げたこの投稿を見てきましたが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>;
      }
   }
}

上限と下限の両方が不明な配列が与えられた場合はどうなりますか?

4

1 に答える 1

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;
}
于 2012-02-08T05:19:12.237 に答える