0

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]);
}
andre_lamothe
  • 2,171
  • 2
  • 41
  • 74
  • I see no vector of vectors. There is usually no point to store vector itself on the heap, it already stores its elements on the heap anyway, so you are only pushing the three pointers it contains to the heap. Why store `DPoint` by 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. – Quimby Nov 10 '22 at 07:50
  • You don't have any `delete`s for all your `new`s. – Thomas Weller Nov 10 '22 at 07:52
  • @ThomasWeller that's why I want to remove the new, and make vector of vectors – andre_lamothe Nov 10 '22 at 07:55
  • @Quimby Can you make an answer with the suggestions, I didn't understand it – andre_lamothe Nov 10 '22 at 07:55
  • Maybe you want [std::array](https://stackoverflow.com/questions/39548254/does-stdarray-guarantee-allocation-on-the-stack-only) – Thomas Weller Nov 10 '22 at 07:56
  • Why a vector of vectors? This looks like a situation for a `vector pixelSpacing` (no pointers in the vector, no pointer to the vector) – harold Nov 10 '22 at 07:56
  • @harold That's what I want... – andre_lamothe Nov 10 '22 at 07:57
  • @harold can you tell me the syntax of initializing it ? – andre_lamothe Nov 10 '22 at 07:59
  • Sure, here you go: [Initializing the size of a C++ vector](https://stackoverflow.com/q/25108854/555045) – harold Nov 10 '22 at 08:00

2 Answers2

1

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.

KeyC0de
  • 4,728
  • 8
  • 44
  • 68
1

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*/);
}
Quimby
  • 17,735
  • 4
  • 35
  • 55