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]);
}
asked Nov 10, 2022 at 7:46
Andre Ahmed
1,9394 gold badges43 silver badges79 bronze badges
2 Answers 2
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*/);
}
answered Nov 10, 2022 at 8:02
Quimby
19.4k4 gold badges40 silver badges61 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Nov 10, 2022 at 7:50
KeyC0de
5,35710 gold badges55 silver badges74 bronze badges
3 Comments
Thomas Weller
The vector can be allocated on the stack. Its elements are allocated in the free store.
Andre Ahmed
I want to remove the news..
Andre Ahmed
Can you show me the equivelent of the above code using std::array ?
lang-cpp
DPointby pointer again? Why not just by value? You should use pointers because you need to manually manage lifetime or refer to objects, no just because they are non-primitive types, this is not Java.deletes for all yournews.