Andre Ahmed
Andre Ahmed

Reputation: 1891

converting heap based vector to stack

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]);
}

Upvotes: 0

Views: 115

Answers (2)

Quimby
Quimby

Reputation: 19223

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*/);
}

Upvotes: 1

KeyC0de
KeyC0de

Reputation: 5287

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.

Upvotes: 1

Related Questions