[SOLVED] Speeds of 3D Vector Versus 3D Array of Varying Size

Issue

I’m designing a dynamic hurtbox for characters in a text-based game, which catches the locations of hits (or misses) of a weapon swung at them. The location (indices) and damage (magnitude) of hits are then translated into decreases in corresponding limb health variables for a character. My thoughts are that this hurtbox would best be implemented using a class with some 3D vector/array member.

Naturally, I might want varying dimensions of the 3D container for different sizes of enemy, but I’m aware that size is usually determined upon initialization. So here’s my question:

Would it be more efficient to use a C-style dynamic array, the size of which I can decide and allocate inside a parameterized constructor, like so?

class hurtBox {
 private:
   int ***hurtBoxMatrix;
 public:
   hurtBox(int l, int w, int h) {
     hurtBoxMatrix = new int**[l];
     for (int i = 0; i < l; i++) {
       hurtBoxMatrix[i] = new int*[w];
       for (int j = 0; j < w; j++) {
         hurtBoxMatrix[i][j] = new int[h] ();
       }
     }
   }
};

Or, would a vector that I push elements into, up to my desired dimensions, suffice?

class hurtBox {
 private:
   vector<vector<vector<int>>> hurtBoxMatrix;
 public:
   hurtBox(int l, int w, int h) {
     for (int i = 0; i < l; i++) {
       hurtBoxMatrix.push_back(vector<vector<int>>);
       for (int j = 0; j < w; j++) {
         hurtBoxMatrix[i].push_back(vector<int>);
         for (int k = 0; k < h; k++) {
           hurtBoxMatrix[i][j].push_back(0);
         }
       }
     } 
   }
};

I imagine the former, since that first allocation is constant time, right? Is there a way to do this that’s better than either of these?

Thanks in advance.

Solution

You’d be better off simply allocating the 3D array in a single allocation, and use indexing to access the elements. Allocation for the std::vector storage can then be handled in the constructor for std::vector.

In general it’s best to avoid:

  1. multiple allocations
  2. repeatedly calling push_back
class hurtBox {
 private:
   vector<int> hurtBoxMatrix;
   int m_l;
   int m_w;
   int m_h;
 public:
   hurtBox(int l, int w, int h) 
      : hurtBoxMatrix(l * w * h), m_l(l), m_w(w), m_h(h) {}

   int& operator (int i, int j, int k) {
     return hurtBoxMatrix[ I*m_w*m_h + j*m_w + k ];
   }
   const int operator (int i, int j, int k) const {
     return hurtBoxMatrix[ i*m_w*m_h + j*m_w + k ];
   }
};

Answered By – robthebloke

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *