Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is storing pointers in std::vector ruining it's advantage of continuous memory storage

Tags:

c++

containers

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?

like image 540
Barış Uşaklı Avatar asked May 26 '13 19:05

Barış Uşaklı


1 Answers

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).

like image 197
CrazyCasta Avatar answered Sep 29 '22 06:09

CrazyCasta