Three dimensional arrays of integers in C++

前端 未结 7 1564
野的像风
野的像风 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:08

    There are many advantages to using the STL to manage your memory over using new/delete. The choice of how to represent your data depends on how you plan to use it. One suggestion would be a class that hides the implementation decision and provides three dimensional get/set methods to a one dimensional STL vector.

    If you really believe you need to create a custom 3d vector type, investigate Boost first.

    // a class that does something in 3 dimensions
    
    class MySimpleClass
    {
    public:
    
      MySimpleClass(const size_t inWidth, const size_t inHeight, const size_t inDepth) :
       mWidth(inWidth), mHeight(inHeight), mDepth(inDepth)
       {
           mArray.resize(mWidth * mHeight * mDepth);
       }
    
    
      // inline for speed
      int Get(const size_t inX, const size_t inY, const size_t inZ) {
         return mArray[(inZ * mWidth * mHeight) + (mY * mWidth) + mX];
      }
    
      void Set(const size_t inX, const size_t inY, const size_t inZ, const int inVal) {
         return mArray[(inZ * mWidth * mHeight) + (mY * mWidth) + mX];
      }
    
      // doing something uniform with the data is easier if it's not a vector of vectors
      void DoSomething()
      {
         std::transform(mArray.begin(), mArray.end(), mArray.begin(), MyUnaryFunc);
      }
    
    private:
    
      // dimensions of data
      size_t mWidth;
      size_t mHeight;
      size_t mDepth;
    
      // data buffer
      std::vector< int > mArray;
    };
    

提交回复
热议问题