If you are adding items to the back of a sequence and removing them from the front, then the preferred container type is a
deque (double-ended queue.) This supports almost identical functionalty as the vector, including random access. The exception is that it does not provide contiguous storage and can therefore not be used like a C-style buffer. And allows for fast inserts and removals from the front as well as the back of the sequence.
The
list comes into its own when you need to remove and insert things from arbitrary positions in the sequence. But as it does not support random access.
A
vector is good when you are adding and removing mainly from the end, and when the sequence it pretty much fixed. It supports random access and is the only one of the containers to guarantee contiguous storage.
(There is a school of thought that the deque should be the default choice of container; that you should only switch to vector when you need contiguous storage and list when you need to be able to insert and remove frequently from arbitrary positions in the sequence.)
Andy
PS Supporting information
A. Results from:
Analysis of List class uses
http://www.openoffice.org/tools/performance/list_classes.html
Operation list vector deque OOo List
Create 10000e 1762 231 126 1068
Delete 10000e 1513 22 56 12
Remove Front 10000e 1711 n/a 85 7975
Remove Back 10000e 1720 13 82 1064
Iteration 10000e 57 13 28 13
NOTE: all times are in u-seconds |
(I'm not sure what the Ooo List class is; the Open Office guy's own list implementaton, I presume.)
B. Baptiste Wicht's performance benchmarks
C++ benchmark – std::vector VS std::list VS std::deque
http://www.baptiste-wicht.com/2012/12/cpp-benchmark-vector-list-deque/
C. Herb Sutter on why you should prefer deque
Using Vector and Deque
http://www.gotw.ca/gotw/054.htm