burnedWood
burnedWood

Reputation: 93

Iterate through a boost::multi_array view

I want to understand how to use the view functionality provided by boost::multi_array. Specifically, I want to be able to iterate within a single loop over all elements of a view that represents a particular submatrix of the initial matrix (not necessarily continuous). It seems that the iterator provided will not do what I want (or anything, it will not compile).

In the following example, I have a 2x6 matrix and I want to get its 2x4 submatrix so, if I try to print it I would expect to get "BoosLion". Indeed this is the case if I iterate for each dimension. But when I try to do the iteration with a single iterator, the program will not compile.

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


int main()
{
  boost::multi_array<char, 2> a{boost::extents[2][6]};

  a[0][0] = 'B';
  a[0][1] = 'o';
  a[0][2] = 'o';
  a[0][3] = 's';
  a[0][4] = 't';
  a[0][5] = '\0';

  a[1][0] = 'L';
  a[1][1] = 'i';
  a[1][2] = 'o';
  a[1][3] = 'n';
  a[1][4] = 's';
  a[1][5] = '\0';
  typedef boost::multi_array<char, 2>::array_view<2>::type array_view;
  typedef boost::multi_array_types::index_range range;
  array_view b = a[boost::indices[range{0,2}][range{0,4}] ];

  for (unsigned int i = 0; i < 2; i++ ) {
    for (unsigned int j = 0; j < 4; j++ ) {
      std::cout << b[i][j] << std::endl;
    }
  }
//  I want to do something like this:
//  for (auto itr = b.begin(); itr < b.end(); ++itr) {
//    std::cout << *itr << std::endl;
//  }
}

Does anyone know how to iterate with only a single loop? I tried searching the documentation but have been unable to find anything relevant. Also, if anyone knows of another library that can do this, let me know, thank you!

Upvotes: 0

Views: 1349

Answers (2)

astroboylrx
astroboylrx

Reputation: 891

update2

Based on the answer provided by @rhashimoto, I tried to make some generalization. With the following functions

// moving the judgement of dimensionality to the function's return-type
template<class T, class F>
typename std::enable_if<(T::dimensionality==1), void>::type IterateArrayView(T& array, F f) {
    for (auto& element : array) {
        f(element);
    }
}

template<class T, class F>
typename std::enable_if<(T::dimensionality>1), void>::type IterateArrayView(T& array, F f) {
    for (auto element : array) {
        IterateArrayView<decltype(element), F>(element, f);
    }
}

// given f() takes extra arguments
template<class T, class F, class... Args>
typename std::enable_if<(T::dimensionality==1), void>::type IterateArrayView(T& array, F f, Args& ...args) {
    for (auto& element : array) {
        f(element, args...);
    }
}

template<class T, class F, class... Args>
typename std::enable_if<(T::dimensionality>1), void>::type IterateArrayView(T& array, F f, Args& ...args) {
    for (auto element : array) {
        IterateArrayView<decltype(element), F, Args...>(element, f, args...);
    }
}

you can apply a function to each element with extra arguments. For example

int main() {
    using array_type = boost::multi_array<int, 3>;
    using view_type = array_type::array_view<3>::type;
    using range = boost::multi_array_types::index_range;

    array_type data;
    data.resize(boost::extents[16][4][4]);
    view_type view = data[boost::indices[range(0,4)][range()][range()]];

    int count = 0;
    IterateArrayView(view, [](int &i, int &count) { i = count++;}, count);
    std::cout << view[3][3][3] << std::endl; // output 63 (=4^3-1)

    return 0;
}

wrong and old solution below

In fact, boost::multi_array_view provide a method called origin() (ref: here):

template <typename T, std::size_t NumDims>
class multi_array_view :
  public const_multi_array_view<T,NumDims,T*>
{
    // a lot of code ...
    element* origin() { return this->base_+this->origin_offset_; }
    // a lot of code ...
};

So you can loop through it by

array_view b;
for (auto it = b.origin(); it != b.origin()+b.num_elements(); it++) {
    // do something, e.g.
    *it = 'a';
}

For boost::multi_array, you can use auto it = b.data() instead.

update1: Sorry, my solution was incorrect. I just found that, although b.origin() gives you the correct iterator to begin with, you are still looping through the multi_array instead of this array_view.

Upvotes: 0

rhashimoto
rhashimoto

Reputation: 15841

Here is one way to do this:

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

// Functor to iterate over a Boost MultiArray concept instance.
template<typename T, typename F, size_t Dimensions = T::dimensionality>
struct IterateHelper {
   void operator()(T& array, const F& f) const {
      for (auto element : array)
         IterateHelper<decltype(element), F>()(element, f);
   }
};

// Functor specialization for the final dimension.
template<typename T, typename F>
struct IterateHelper<T, F, 1> {
   void operator()(T& array, const F& f) const {
      for (auto& element : array)
         f(element);
   }
};

// Utility function to apply a function to each element of a Boost
// MultiArray concept instance (which includes views).
template<typename T, typename F>
static void iterate(T& array, const F& f) {
   IterateHelper<T, F>()(array, f);
}

int main() {
   boost::multi_array<char, 2> a{boost::extents[2][6]};

   a[0][0] = 'B';
   a[0][1] = 'o';
   a[0][2] = 'o';
   a[0][3] = 's';
   a[0][4] = 't';
   a[0][5] = '\0';

   a[1][0] = 'L';
   a[1][1] = 'i';
   a[1][2] = 'o';
   a[1][3] = 'n';
   a[1][4] = 's';
   a[1][5] = '\0';

   typedef boost::multi_array<char, 2>::array_view<2>::type array_view;
   typedef boost::multi_array_types::index_range range;
   array_view b = a[boost::indices[range{0,2}][range{0,4}] ];

   // Use the utility to apply a function to each element.
   iterate(b, [](char& c) {
      std::cout << c << std::endl;
   });

   return 0;
};

The code above defines a utility function iterate(), to which you pass an object satisfying the Boost MultiArray concept (which includes views) and a function to apply to each element. The utility function works by using a Functor that iterates over each dimension recursively.

CoLiRu

Upvotes: 3

Related Questions