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]);
}
asked Nov 10, 2022 at 7:46
9
  • 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. Commented Nov 10, 2022 at 7:50
  • You don't have any deletes for all your news. Commented Nov 10, 2022 at 7:52
  • @ThomasWeller that's why I want to remove the new, and make vector of vectors Commented Nov 10, 2022 at 7:55
  • @Quimby Can you make an answer with the suggestions, I didn't understand it Commented Nov 10, 2022 at 7:55
  • Maybe you want std::array Commented Nov 10, 2022 at 7:56

2 Answers 2

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*/);
}
answered Nov 10, 2022 at 8:02
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Nov 10, 2022 at 7:50

3 Comments

The vector can be allocated on the stack. Its elements are allocated in the free store.
I want to remove the news..
Can you show me the equivelent of the above code using std::array ?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.