Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a vector of object values from a vector of object pointers?

Tags:

c++

c++11

The "naive" solution is;

std::vector<T> vector_of_objects;
vector_of_objects.reserve(vector_of_pointers.size());
for (T const * p : vector_of_pointers)
    vector_of_objects.push_back(*p);

The above seems cumbersome and perhaps not immediately obvious.

Is there a solution that is at least not significantly less efficient and perhaps a little quicker and more intuitive? I'm thinking C++11 might have a solution that I am not aware of...

like image 822
quant Avatar asked Sep 27 '13 11:09

quant


People also ask

What is the difference between a vector and a vector of pointers?

Having vector of objects is much slower than a vector of pointers. Here’s another result when the size of a Particle object is increased to 128 bytes (previously it was 72 bytes):

How to access pointers in a vector and print them out?

We are using the & (address of) operator to access pointers in the vector and print them out to the console. Note that these memory addresses are located on the stack memory. Video Player is loading. This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window.

Why is it wrong to push an object to a vector?

It is equally wrong to push the object on the vector first and then push a pointer to the object on the vector using absorbList.push_back ( &meshList.back () ) because vector::push_back will reallocate the whole vector, invalidating all pointers.

What is an vector vector of objects?

Vector of objects is just a regular vector with one call to the update method. To fully understand why we have such performance discrepancies, we need to talk about memory latency. Here’s a great summary that explains the problem:


1 Answers

Does writing everything in one line mean shorter code? No.

In my opinion these two lines are shorter and more readable:

for (auto p : vector_of_pointers)

    vector_of_objects.emplace_back(*p);

 

Function std::for_each is not shorter than ranged-based loop, sometime it's bigger due to passing lambda expressions.

Function std::transform is even longer than std::for_each, however the word transform is an advantage to find out what's happening in the following.

like image 104
masoud Avatar answered Oct 14 '22 03:10

masoud