0

I would like cell indices of a contiguous (box-shaped) area area in a 3d grid, i.e. a 3d set {iMin…iMax}×{jMin…jMax}×{kMin…kMax}. The naive approach would be:

for(int i=iMin; i<=iMax; i++){
  for(int j=jMin; j<=jMax; j++){
    for(int k=kMin; k<=kMax; k++){
      // ...
    }
  }
}

Is there a less verbose way to do that, without nested loops?

(I am in c++11 and have a Vector3i class for coordinates. I can use any boost library, also.)

eudoxos
  • 18,545
  • 10
  • 61
  • 110
  • As contiguity cannot not be guaranteed in full generality; I doubt it. The three loops will probably be faster (and certainly clearer) than one iterating variable and an elaborate mapping algorithm from that to the coordinates. – Bathsheba Jul 10 '13 at 08:30
  • If you have control over the `Vector3i` class, you could overload `operator[]` if you wanted. However, what's the problem with nested loops? That way, it's very clear to every reader of your code what you're doing. – arne Jul 10 '13 at 08:55
  • `Vector3i` is from [Eigen](http://eigen.tuxfamily.org); it already defines `operator[]`. Nested loops take three lines and it is easy to mistype something. – eudoxos Jul 10 '13 at 09:05
  • @Bathsheba: the range IS contiguous, I am pretty sure about that. – eudoxos Jul 10 '13 at 12:04

2 Answers2

0

One way would be wrapping you 3 fors into algorithm for_each_3d and pass it a lambda, but it will only work for 3d and accessing neighboring elements would be a pain. Or you can use boost_mutli array and loop similar to this: how to traverse a boost::multi_array Note, that multi_array is an array and cannot be resized after construction

Community
  • 1
  • 1
aryan
  • 621
  • 3
  • 10
0

If you want a single loop you can go for something like this:

int main()
{
  size_t const N=8, M=N*N*N;
  size_t x(0), y(0), z(0);
  for (size_t i=0; i<M; ++i)
  {
    std::cout << x << ", " << y << ", " << z << std::endl;
    ++z;
    if (z == N)
    {
      z=0;
      ++y;
      if (y == N)
      {
        y=0;
        ++x;
      }
    }
  }
}

But don't say I told you it looks nice! ;)

Pixelchemist
  • 24,090
  • 7
  • 47
  • 71