9

I have been looking into the boost::multi_array library in search of an iterator that allows you to traverse the whole multi_array in a single for loop.

I don't think there is any such iterator in that library. (The iterators that are found there let you traverse a single dimension of the multi_array)

Am I wrong?
If not, is there any library that defines such an iterator?

Entering into details, I'd like to write something like:

boost::multi_array< double, 3 > ma(boost::extents[3][4][2]);  

for( my_iterator it = ma.begin(); it != ma.end(); ++it )  
{  
    // do something  
    // here *it has element type (in this case double)  
}  

and obtain a loop that repeats 3x4x2 times

Mat
  • 202,337
  • 40
  • 393
  • 406
Jon Snow
  • 91
  • 1
  • 2

1 Answers1

11

You can use an implementation of std::for_each from <algorithm> to access each individual element. There is an example in the Boost documentation

Alternatively, you can use array::origin() and array::num_elements() as follows:

boost::multi_array< double, 3 > ma(boost::extents[3][4][2]);  

for(auto i = ma.origin(); i < (ma.origin() + ma.num_elements()); ++i)  
{  
    // do something with i
}  
Maarten
  • 1,037
  • 1
  • 11
  • 32
  • 7
    I believe you want ma.data() rather than ma.origin() for the concrete boost::multi_array and boost::multi_array_ref classes. origin() will do the wrong thing for non-zero index_bases() while data() will work correctly. – Rhys Ulerich Apr 13 '11 at 03:13
  • 1
    @Maarten That example in the link shows boost::for_each (not std::for_each), which expects a range iterator, right (versus a start and end in the std version)? multi_array didn't seem to provide either of these (.begin/end() or the automatic range iterator) in my experiment. – David Doria Feb 23 '16 at 14:47