Reputation: 12435
I would like some advice on which STL container best meets the following needs:
Thread safety is not required.
Here are my thoughts:
list: Requires a separate allocation for each element. More expensive traversal.
vector: Need to be reallocated as the collection grows. Best sort and traversal performance.
deque: Fewer allocations than list and fewer reallocations than vector. I don't know about behavior with respect to sort.
I am currently using list. The flowchart at In which scenario do I use a particular STL container? leads me to deque.
My knowledge of STL is old; I don't know about container types that have been added since 2003, so maybe there's something well-suited that I've never heard of.
Upvotes: 1
Views: 95
Reputation: 249113
std::vector<T*>
will be the winner based on the points discussed.
Don't be afraid of the resizing that will need to occur--just reserve()
a reasonable amount (say 500 if many of your collections will be around there).
Sorting performance with vector<T*>
will also be very good.
Allocation and deallocation of each T
will be important. Pay attention to this. For example you may want to allocate thousands of T
s at a time, to reduce the memory allocation overhead (and make it faster to deallocate everything at the end). This is known as an "arena" or "pool". You can probably store 32-bit relative pointers into the arena, saving half the pointer storage space.
And of course, if T
is small you might consider storing it by value instead of by pointer.
Upvotes: 3