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...
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):
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With