The cost table: what each container really costs
Every data structure is a trade-off between how fast you can find, add and remove things, and how much memory and cache-friendliness you give up to get there. C++ makes those costs visible: the standard guarantees the complexity of every container operation, so choosing a container is choosing a row of the table below.
| Container | Index | Find | Insert | Remove | Notes |
|---|---|---|---|---|---|
std::vector | O(1) | O(n) | O(1) amortised at end, O(n) elsewhere | O(1) at end, O(n) elsewhere | Contiguous memory. The default choice. |
std::deque | O(1) | O(n) | O(1) at both ends | O(1) at both ends | Chunked blocks; backs std::queue. |
std::list / forward_list | — | O(n) | O(1) at a known iterator | O(1) at a known iterator | One heap node per element; slow to walk. |
std::unordered_map / set | — | O(1) average, O(n) worst | O(1) average | O(1) average | Hash table. No order. |
std::map / set | — | O(log n) | O(log n) | O(log n) | Balanced tree (red-black). Sorted order, lower_bound. |
std::priority_queue | top only, O(1) | — | O(log n) | O(log n) top only | Binary heap inside a vector. |
std::stack / std::queue | top/front only | — | O(1) | O(1) | Adapters over deque (or vector/list). |
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{10, 20, 30};
v.push_back(40); // amortised O(1): add at the end
std::cout << v[2] << '\n'; // O(1): jump straight to index 2
v.insert(v.begin(), 5); // O(n): every element shifts right
v.pop_back(); // O(1): remove from the end
for (int x : v) std::cout << x << ' ';
std::cout << "\nsize " << v.size() << '\n';
}30
5 10 20 30
size 4The same container, three different costs depending on where you touch it.
Replace v.insert(v.begin(), 5) with a std::deque and push_front(5). Which operation got cheaper, and which one did you give up nothing for?
std::unique_ptr, so you see what the library is doing for you. Then it shows the STL version you should actually use at work. Interviews ask for the first; code reviews expect the second.