I’m using queue’s and priority queues, through which I plan on pumping a lot of data quite quickly.
Therefore, I want my q’s and pq’s to be responsive to additions and subtractions.
What are the relative merits of using a vector, list, or deque as the underlying container?
Update:
At the time of writing, both Mike Seymour and Steve Townsend’s answers below are worth reading. Thanks both!
The only way to be sure how the choice effects performance is to measure it, in a situation similar to your expected use cases. That said, here are some observations:
For
std::queue:std::dequeis usually the best choice; it supports all the necessary operations in constant time, and allocates memory in chunks as it grows.std::listalso supports the necessary operations, but may be slower due to more memory allocations; in special circumstances, you might be able to get good results by allocating from a dedicated object pool, but that’s not entirely straightforward.std::vectorcan’t be used as it doesn’t have apop_front()operation; such an operation would be slow, as it would have to move all the remaining elements.A potentially faster, but less flexible, alternative is to implement a circular buffer over a fixed-size array (e.g.
std::array, or astd::vectorthat you don’t resize). You’ll need to deal with the case of it filling up, either by reporting an error, or allocating a larger buffer and copying all the data.For
std::priority_queue:std::vectoris usually the best choice; it grows exponentially (reducing the number of memory allocations), and is a simple data structure that’s very fast to access – an iterator can be implemented simply as a wrapper around a pointer.std::dequemay be slower as it typically grows linearly (requiring more memory allocation), and access is more complicated than with a vector.std::listcan’t be used as it doesn’t provide random access.To summarise – the defaults are usually the best choice, but if speed really is important, then measure the alternatives.