Three dimensional arrays of integers in C++

前端 未结 7 1560
野的像风
野的像风 2020-12-17 00:05

I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 00:06

    Have a look at the Boost multi-dimensional array library. Here's an example (adapted from the Boost documentation):

    #include "boost/multi_array.hpp"
    
    int main() {
      // Create a 3D array that is 20 x 30 x 4
      int x = 20;
      int y = 30;
      int z = 4;
    
      typedef boost::multi_array array_type;
      typedef array_type::index index;
      array_type my_array(boost::extents[x][y][z]);
    
      // Assign values to the elements
      int values = 0;
      for (index i = 0; i != x; ++i) {
        for (index j = 0; j != y; ++j) {
          for (index k = 0; k != z; ++k) {
            my_array[i][j][k] = values++;
          }
        }
      }
    }
    

提交回复
热议问题