Home > front end >  converting heap based vector to stack
converting heap based vector to stack

Time:11-10

I would like to convert it to vector of vectors but I'm confused about the code above it's better to store it on stack rather than heap, that's why I want to change it to vector of vector

std::vector<DPoint*>* pixelSpacing;    ///< vector of slice pixel spacings
pixelSpacing = new std::vector<DPoint*>(volume.pixelSpacing->size());
for (unsigned int i = 0; i < pixelSpacing->size(); i  )
{
   (*pixelSpacing)[i] = new DPoint(*(*volume.pixelSpacing)[i]);
}

CodePudding user response:

Okay, as per the comment, I am making an answer.

std::vector<DPoint> pixelSpacing(volume.pixelSpacing->size()); 
for (unsigned int i = 0; i < pixelSpacing.size(); i  )
{
   pixelSpacing[i] = DPoint(/*DPoint constructor args*/);
}

Or alternatively:

std::vector<DPoint> pixelSpacing;
//Reserving size is optional.
pixelSpacing.reserve(volume.pixelSpacing->size());
for (unsigned int i = 0; i < volume.pixelSpacing->size(); i  )
{
   pixelSpacing.emplace_back(/*DPoint constructor args*/);
}

CodePudding user response:

An std::vector is allocated on the heap. There's no way to "convert it" so that it allocates stuff on the stack. You may create a new vector-like sequence container that allocates on the stack is one thing you can do. Or you can use std::array which allocates on the stack by default.

  •  Tags:  
  • c
  • Related