Iterate over size boost :: multi_array

I am trying to write some size-independent code for a template class in C ++ using boost :: multi_array (although if other containers / data structures are better at this, I would be happy to hear about that).

Given the dimension, I would like to iterate over the entire range of all other dimensions, returning a 1d representation of the selected size. This is pretty simple, or at least it looks like documentation on speeding up.

What I cannot figure out how to do this is to iterate over the selected dimension across all array sizes when the array size is known at compile time.

Any tips on how to do this?

+3
source share
1 answer

boost:: multi_array, 2D- 3D-:

#include "boost/multi_array.hpp"
#include <cassert>
#include <iostream>

int main()
{
    typedef boost::multi_array<double, 3> array_type;
    typedef array_type::index index;

    array_type myArray3D(boost::extents[3][4][2]);

    // Assign values to the elements
    int values = 0;
    for (index i = 0; i != 3; ++i)
    {
            for (index j = 0; j != 4; ++j)
            {
                    for (index k = 0; k != 2; ++k)
                    {
                            myArray3D[i][j][k] = values++;
                    }
            }
    }
    // Verify values
    int verify = 0;
    for (index i = 0; i != 3; ++i)
    {
            for (index j = 0; j != 4; ++j)
            {
                    for (index k = 0; k != 2; ++k)
                    {
                            std::cout << "[" << i << "]";
                            std::cout << "[" << j << "]";
                            std::cout << "[" << k << "] = ";
                            std::cout << myArray3D[i][j][k] << std::endl;
                            assert(myArray3D[i][j][k] == verify++);
                    }
            }
    }

    typedef boost::multi_array_types::index_range range;
    array_type::index_gen indices;

    // Create a new view with 2 dimentions fixing the 2nd dimention to 1
    array_type::array_view<2>::type myView =
    myArray3D[indices[range()][1][range()]];
    std::size_t numDims = myView.size();
    std::cout << "numDims = " << numDims << std::endl;

    for (index i = 0; i != 3; ++i)
    {
            for (index j = 0; j != 2; ++j)
            {
                    std::cout << "[" << i << "]";
                    std::cout << "[" << j << "] = ";
                    std::cout << myView[i][j] << std::endl;
            }
    }

    return 0;
}
+1

All Articles