Legacy C++ › 6. The Standard Template Library
Sequence Containers
vector, deque and list, and how to choose between them.
Explanation
The STL’s sequence containers store elements in a user-chosen order:
| Container | Storage | Good at | Weak at |
|---|---|---|---|
std::vector<T> |
contiguous array | random access, append at end, cache friendliness | insert/erase in the middle or front |
std::deque<T> |
chunked array | fast push/pop at both ends, random access | middle insert; not contiguous |
std::list<T> |
doubly linked nodes | insert/erase anywhere given an iterator, stable iterators | no random access, poor cache use |
Default choice: vector. Use deque for queues at both ends, list only when you really need stable iterators or cheap splicing.
vector capacity grows geometrically; reserve(n) avoids reallocations. When it reallocates, all iterators, pointers and references to elements are invalidated.
Example
#include <deque>
#include <iostream>
#include <list>
#include <vector>
int main() {
std::vector<int> v;
v.reserve(10);
for (int i = 0; i < 5; ++i) v.push_back(i * i); // 0 1 4 9 16
v.insert(v.begin() + 2, 99); // O(n)
v.erase(v.begin()); // O(n)
std::cout << v.size() << " front=" << v.front() << " back=" << v.back()
<< " v[2]=" << v[2] << "\n";
std::deque<int> d;
d.push_back(1); d.push_front(0); d.push_back(2); // 0 1 2
std::cout << d[1] << "\n";
std::list<int> l(v.begin(), v.end());
for (std::list<int>::iterator it = l.begin(); it != l.end(); ) {
if (*it % 2 == 0) it = l.erase(it); // erase returns the next iterator
else ++it;
}
for (std::list<int>::const_iterator it = l.begin(); it != l.end(); ++it)
std::cout << *it << " ";
std::cout << "\n";
std::vector<int>().swap(v); // release memory (shrink idiom)
return 0;
}
Common pitfalls
- Holding an iterator/reference into a
vectoracrosspush_backorinsert: it may dangle. - Erasing inside a loop with
it++aftereraseis undefined. Useit = c.erase(it). v[i]does no bounds checking;v.at(i)throwsstd::out_of_range.std::vector<bool>is a packed special case and not a real container ofbool.- Calling
front()/back()/pop_back()on an empty container is undefined.
Legacy vs modern
C++11 adds emplace_back, move semantics (cheap reallocation), initializer lists (std::vector<int> v = {1,2,3};), shrink_to_fit, std::array and std::forward_list. See Move Semantics and unique_ptr.
Exercises
1. Why is vector usually faster than list even for middle insertions of small elements?
Contiguous memory is cache-friendly, while list nodes are scattered and each insertion allocates; for small elements the shifting cost is smaller than the pointer-chasing and allocation cost.