I have a 1d array containing Nd data, I would like to effectively traverse on it with std::transform or std::for_each.
unigned int nelems;
unsigned int stride=3;// we are going to have 3D points
float *pP;// this will keep xyzxyzxyz...
Load(pP);
std::transform(pP, pP+nelems, strMover<float>(pP, stride));//How to define the strMover??
The answer is not to change
strMover
, but to change your iterator. Define a new iterator class which wraps afloat *
but moves forward 3 places whenoperator++
is called.You can use boost's Permutation Iterator and use a nonstrict permutation which only includes the range you are interested in.
If you try to roll your own iterator, there are some gotchas: to remain strict to the standard, you need to think carefully about what the correct "end" iterator for such a stride iterator is, since the naive implementation will merrily stride over and beyond the allowed "one-past-the-end" to the murky area far past the end of the array which pointers should never enter, for fear of nasal demons.
But I have to ask: why are you storing an array of 3d points as an array of
float
s in the first place? Just define aPoint3D
datatype and create an array of that instead. Much simpler.use boost adapters. you can get iterators out of them. the only disadvantage is compilation time.
Well, I have decided to use for_each instead of transform any other decisions are welcome:
where
From first look this is a thread safe solution.
This is terrible, people told you to use stride iterators instead. Apart from not being able to use functional objects from standard library with this approach, you make it very, very complicated for compiler to produce multicore or sse optimization by using crutches like this. Look for "stride iterator" for proper solution, for example in c++ cookbook.
And back to original question... use valarray and stride to simulate multidimensional arrays.