title: C++: Deallocating 3d vector
body: <p>For slic superpixel creation for a 3d medical image I've created a 3d vector 
  (std::vector of std::vector of std::vector holding DataStr objects). With the dimensions of the image (~150 x 150 x 150). DataStr is a struct that stores voxel information such as a vector of pointers to its neighbors in the same 3d vector. Working with this turns out to be much faster than looping through the image with a neighborhood iterator or KdTree nearest neighbor search as this information has to be available for each iteration of the slic algorithm. Furthermore, it is in comparison very convenient to work with it. However, the deallocation of the 3d vector takes ~4 minutes, when the 3d vector runs out of scope. Can anyone tell me why this is the case and how I can avoid this? Thanks!</p>
  
  <p>Edit:</p>
  
  <p>First time asking a question here, thanks for your patience :-)!</p>
  
  <pre><code>struct DataStr{
    std::vector&lt;DataStr*&gt; neighbors;
    float cmpVal;
    int association;
    cv::Mat index;
    float intensity;
    DataStr() :association{ -1 }, cmpVal{ std::numeric_limits&lt;float&gt;::max() }{}
  };
  </code></pre>
  
  <p>Above is the struct in the .hpp file. Below definition and initialization of dat</p>
  
  <pre><code>std::vector&lt;std::vector&lt;std::vector&lt;DataStr&gt;&gt;&gt; dat;
  for (int i{ 0 }; i &lt; imgDim[0]; ++i)
  {
      dat.resize(imgDim[0]);
      for (int j{ 0 }; j &lt; imgDim[1]; ++j)
      {
          dat[i].resize(imgDim[1]);
          for (int k{ 0 }; k &lt; imgDim[2]; ++k)
          {
              dat[i][j].resize(imgDim[2], DataStr{});
          }
      }
  }
  </code></pre>
  
  <p>imgDim is 3d array of image dimension.</p>
  
  <pre><code> for (it_nImg.GoToBegin(), it_nMask.GoToBegin(), it_nCent.GoToBegin();    !it_nImg.IsAtEnd(); ++it_nImg, ++it_nMask, ++it_nCent)
  {       
      auto  idx = it_nMask.GetIndex();
      DataStr* str = &amp;dat[idx[0]][idx[1]][idx[2]];
      (*str).intensity = it_nImg.GetCenterPixel();
      (*str).index = (cv::Mat_&lt;float&gt;(1, 3) &lt;&lt; idx[0], idx[1], idx[2]);
  
      for (int i = 0; i &lt; it_nMask.Size(); ++i)
      {
          auto tmpIdx = it_nMask.GetIndex(i);
          (*str).neighbors.push_back(&amp;dat[tmpIdx[0]][tmpIdx[1]][tmpIdx[2]]);
      }
  
  }
  </code></pre>
  
  <p>it_n* are image neighborhood iterators from itk library to fill the neighborhood vector in DataStr for each voxel in the image. it_nMask.Size() is the size of the chosen neighborhood. it_n*.GetIndex() provides a 3 element array of the 3d voxel index. Thanks a lot.</p>
  
  <p>Edit edit:</p>
  
  <p>If I store the indices of the neighboring voxels instead of pointers to them the deallocation takes only 0.5 seconds. Is this because the pointers to DataStr are 8 byte in length and an int is only 4 byte on my machine? </p>