Search code examples
c++boostiteratorboost-multi-array

Boost Multiarray Dimensions


I have a Boost multiarray whose dimensions are set at run-time based on input from the user.

I'd now like to iterate over that array via x,y,z components.

If this were a std::vector, I would use:

for(int i=0;i<v.size();i++){

Or perhaps some kind of iterator.

How do I get numeric values of the multiarray's dimensions?

How do I iterate over the multiarray?


Solution

  • You could use shape() for a less convoluted way:

    #include <iostream>
    #include <string>
    #include <boost/multi_array.hpp>
    
    int main() {
        boost::multi_array<std::string, 2> a(boost::extents[3][5]);
        for(size_t x = 0; x < a.shape()[0]; x++) {
            for(size_t y = 0; y < a.shape()[1]; y++) {
                std::ostringstream sstr;
                sstr << "[" << x << ", " << y << "]";
                a[x][y] = sstr.str();
            }
        }
        for(size_t x = 0; x < a.shape()[0]; x++) {
            for(size_t y = 0; y < a.shape()[1]; y++) {
                std::cout << a[x][y] << "\n";
            }
        }
        return 0;
    }
    

    (See it in action on coliru)