std::vector
stores it's elements continuously in memory as opposed to std::list
. This gives the std::vector
better performance when iterating over the elements as everything is neatly packed vs jumping all around the memory when iterating a std::list
.
Problem is most of the time I store smart pointers in vectors for polymorphism or for sharing these objects with other parts of the code. Since each object is now allocated dynamically I assume they end up in different memory locations. Is this defeating the purpose of using a std::vector
and essentially turning it into something like a std::list
? Is there anything that can be done to fix this?
I would argue that the biggest advantage of std::vector
over std::list
is that indexing is an O(1) instead of O(n) operation. What you're talking about is a more second order optimization. Also, you're always free to store your own objects all in one big array and then you wouldn't be jumping around as much (if cache purposes is what you're thinking about).
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