Know what each container costs
The objective is to pick a container from its complexity and invalidation guarantees, and to use standard algorithms instead of hand-written loops.
| Container | Structure | Access / find | Insert / erase | Notes |
|---|---|---|---|---|
vector | contiguous array | index ; find , or if sorted | at the back amortised; elsewhere | default choice; cache-friendly |
deque | blocks of arrays | index | at either end ; middle | elements not contiguous overall |
list | doubly linked list | no indexing; find | at a known iterator | stable addresses, poor cache behaviour |
map / set | balanced binary tree (red-black in practice) | sorted iteration; begin() is the minimum | ||
unordered_map / unordered_set | hash table with buckets | average, worst | average | no order; rehashing on growth |
priority_queue | binary heap on a vector | top | push and pop | max-heap by default |
Big-O hides constants that matter in practice. Iterating a vector streams contiguous memory the hardware prefetches; iterating a list or map chases a pointer per element, each possibly a cache miss. For a few hundred elements, a linear scan of a sorted vector often beats a map lookup. Interviewers like to hear both the asymptotic answer and this caveat (QD04 covers cache layout).
std::map::operator[] inserts a default value when the key is missing, so do not use it to test membership; use find, contains (C++20) or count. It also cannot be called on a const map.
Iterator invalidation
An iterator, pointer or reference into a container is invalidated when the operation may have moved or destroyed the element. Using it afterwards is undefined behaviour. The rules worth memorising:
| Container | Insert | Erase |
|---|---|---|
vector | if the size exceeds capacity (reallocation): all invalidated; otherwise those at or after the insertion point | those at or after the erased element |
deque | at either end: all iterators invalidated, but references and pointers stay valid; in the middle: all | at either end: only the erased elements (plus end() at the back); in the middle: all |
list, map, set | none | only the erased element |
unordered_map / set | if it causes a rehash: all iterators, but references and pointers stay valid; otherwise none | only the erased element |
Node-based containers (list, map, set, the unordered family) allocate each element separately, so elements never move. That is why you can safely keep a pointer to an element of a std::map while inserting into it, but not into a std::vector. Calling reserve(n) on a vector up front guarantees no reallocation until the size exceeds n.
Erasing while iterating is the classic trap. erase returns the iterator to the next element; use it instead of incrementing the erased one:
#include <iostream>
#include <map>
int main() {
std::map<long, int> orders{{1, 100}, {2, 0}, {3, 50}, {4, 0}};
for (auto it = orders.begin(); it != orders.end();) {
if (it->second == 0) it = orders.erase(it); // erase returns the next iterator
else ++it;
}
for (const auto& [id, qty] : orders) std::cout << id << ':' << qty << ' ';
std::cout << '\n'; // prints: 1:100 3:50
}
C++20 also offers std::erase_if(container, pred) for every standard container, which does this for you.
The algorithms you should reach for
The <algorithm> and <numeric> headers operate on iterator ranges [first, last):
std::sort: , not stable (introsort).std::stable_sortkeeps the order of equal elements. Both need random-access iterators, so astd::listuses its membersort().std::lower_boundreturns the first element not less than the value;std::upper_boundthe first element greater than it; both are on a sorted random-access range.upper_bound - lower_boundcounts the copies of a value. On astd::map, call the memberm.lower_bound(k): the free function on map iterators is linear because they cannot jump.std::accumulate(first, last, init)folds with+, and the accumulator has the type ofinit. With0instead of0.0, every partial sum is truncated toint.- Erase-remove:
std::remove_ifmoves the kept elements to the front and returns the new logical end;erasethen trims the tail. One pass instead of repeated erases. - Also worth knowing:
std::find_if,std::count_if,std::min_element/std::max_element,std::nth_element(average selection, for medians and percentiles),std::partial_sort(top ), andstd::partial_sum.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<double> fills{0.5, 0.5, 0.5};
std::cout << std::accumulate(fills.begin(), fills.end(), 0) << '\n'; // int init: 0
std::cout << std::accumulate(fills.begin(), fills.end(), 0.0) << '\n'; // 1.5
std::vector<int> px{105, 101, 103, 101, 104};
std::sort(px.begin(), px.end()); // 101 101 103 104 105
auto lo = std::lower_bound(px.begin(), px.end(), 101); // first >= 101
auto hi = std::upper_bound(px.begin(), px.end(), 101); // first > 101
std::cout << "count of 101: " << (hi - lo) << '\n';
auto it = std::lower_bound(px.begin(), px.end(), 102);
std::cout << "first >= 102: " << *it << " at index " << (it - px.begin()) << '\n';
// Erase-remove: drop all prices below 103 in one O(n) pass.
px.erase(std::remove_if(px.begin(), px.end(), [](int p) { return p < 103; }), px.end());
for (int p : px) std::cout << p << ' ';
std::cout << '\n';
}
0
1.5
count of 101: 2
first >= 102: 103 at index 2
103 104 105
The first line is 0, not 1: with an int accumulator, is truncated back to at every step.
Worked example
as-of lookup of the latest quote
You hold quotes sorted by timestamp in a std::vector<Quote> with fields ts and mid. Write a function that returns the latest quote at or before time (an "as-of" join, used to mark trades to the prevailing mid), or nullptr if is earlier than every quote. It must be .
Show solutionHide solution
The latest quote with ts <= t sits just before the first quote with ts > t. That first quote is exactly what std::upper_bound finds. If it is begin(), no quote is at or before . Since we search a vector of Quote by a long, pass a comparator; for upper_bound it is called as comp(value, element).
#include <algorithm>
#include <iostream>
#include <vector>
struct Quote {
long ts; // microseconds since midnight
double mid;
};
// Latest quote at or before t; nullptr if t precedes all quotes.
const Quote* as_of(const std::vector<Quote>& qs, long t) {
auto it = std::upper_bound(qs.begin(), qs.end(), t,
[](long value, const Quote& q) { return value < q.ts; });
if (it == qs.begin()) return nullptr;
return &*std::prev(it);
}
int main() {
std::vector<Quote> qs{{100, 50.00}, {250, 50.05}, {400, 50.10}, {900, 50.00}};
for (long t : {50L, 100L, 399L, 400L, 5000L}) {
const Quote* q = as_of(qs, t);
if (q) std::cout << "t=" << t << " -> quote at " << q->ts << ", mid " << q->mid << '\n';
else std::cout << "t=" << t << " -> no quote yet\n";
}
}
t=50 -> no quote yet
t=100 -> quote at 100, mid 50
t=399 -> quote at 250, mid 50.05
t=400 -> quote at 400, mid 50.1
t=5000 -> quote at 900, mid 50
The edge cases are the point: and land exactly on a quote and must return it (so upper_bound, not lower_bound, which would need a separate equality check), and returns the last quote. Each lookup is one binary search, . The function returns a pointer into the vector, so it is valid only until the vector next reallocates.
Worked example
containers for a price-level order book
Design the containers for an aggregated (price-level) order book that supports: add quantity at a price, cancel quantity at a price, and read the best bid and best ask. Then say what you would change for a book that tracks individual orders by id with time priority.
Show solutionHide solution
Represent prices as integer ticks, never double keys: 100.1 + 0.2 is not exactly 100.3 in floating point, so equal prices could land on different keys.
Each side needs sorted price levels with fast access to the best one, and levels appear and disappear. A std::map gives insert, find and erase over levels and keeps them sorted. Order bids with std::greater<int> so the highest bid is begin(); asks use the default std::less so the lowest ask is begin().
#include <functional>
#include <iostream>
#include <map>
// Prices in integer ticks avoid floating-point keys.
struct OrderBook {
std::map<int, long, std::greater<int>> bids; // best (highest) bid first
std::map<int, long> asks; // best (lowest) ask first
void add(bool is_bid, int px, long qty) {
if (is_bid) bids[px] += qty; // O(log n); creates the level if absent
else asks[px] += qty;
}
void cancel(bool is_bid, int px, long qty) {
auto remove = [&](auto& side) {
auto it = side.find(px);
if (it == side.end()) return;
it->second -= qty;
if (it->second <= 0) side.erase(it); // empty levels must go
};
if (is_bid) remove(bids);
else remove(asks);
}
void print() const {
std::cout << "best bid " << bids.begin()->first << " x " << bids.begin()->second
<< " | best ask " << asks.begin()->first << " x " << asks.begin()->second
<< " | spread " << asks.begin()->first - bids.begin()->first << '\n';
}
};
int main() {
OrderBook ob;
ob.add(true, 10000, 5);
ob.add(true, 10001, 2);
ob.add(false, 10003, 4);
ob.add(false, 10004, 7);
ob.print();
ob.cancel(true, 10001, 2); // best bid level empties and is erased
ob.add(false, 10002, 1); // new best ask
ob.print();
}
best bid 10001 x 2 | best ask 10003 x 4 | spread 2
best bid 10000 x 5 | best ask 10002 x 1 | spread 2
The cancel must erase an emptied level, otherwise begin() would report a best bid of zero size. (print assumes both sides are non-empty; production code checks.)
Order-by-order book. Each price level becomes a FIFO queue of orders (time priority), and cancels arrive by order id, so add an std::unordered_map<OrderId, handle> for average lookup. The handle must stay valid while other orders are added and removed, so the per-level queue should be node-based, such as a std::list<Order> whose iterators survive other insertions and erasures, rather than a std::vector, whose reallocation would invalidate them.
What to say about performance. Tree and list nodes are scattered in memory. Production books often replace the map with a vector of levels indexed by tick offset from a reference price ( access, contiguous), or a sorted vector with the best price at the back, since most activity happens near the top of the book. Mention these as optimisations once the correct design is on the table.
Knowledge check
std::vector<double> v{0.5, 0.5, 0.5}; What does std::accumulate(v.begin(), v.end(), 0) return?
Knowledge check
You keep raw pointers to Order objects stored inside a container while new orders are inserted continuously. With which container can those pointers dangle after an insertion?
Knowledge check
A bid side is stored as std::map<int, long> bids with the default ordering (price ascending). Where is the best (highest) bid?
Key takeaways
vectoris the default;map/setfor sorted data with updates;unordered_mapfor average lookup without order;dequefor both ends;listonly when you need stable positions and splicing.- Vector reallocation invalidates everything; node-based containers never move their elements. Erase while iterating with
it = c.erase(it)orstd::erase_if. - Prefer algorithms:
sort,lower_bound/upper_bound,accumulate(watch the init type), erase-remove,nth_element. - Order books: integer tick prices, a sorted map (or tick-indexed array) per side, and a hash map from order id to a stable handle.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).