Skip to content
LeetQuant
QD03 C++ Fundamentals

QD03 · C++ Fundamentals · Lesson 4 of 6

STL Containers and Algorithms

The complexity of each standard container, which operations invalidate iterators and references, the core algorithms (sort, lower_bound, accumulate, erase-remove), and how to choose containers for an order book.

18 min

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.

ContainerStructureAccess / findInsert / eraseNotes
vectorcontiguous arrayindex O(1)O(1); find O(n)O(n), or O(log⁡n)O(\log n) if sortedat the back O(1)O(1) amortised; elsewhere O(n)O(n)default choice; cache-friendly
dequeblocks of arraysindex O(1)O(1)at either end O(1)O(1); middle O(n)O(n)elements not contiguous overall
listdoubly linked listno indexing; find O(n)O(n)O(1)O(1) at a known iteratorstable addresses, poor cache behaviour
map / setbalanced binary tree (red-black in practice)O(log⁡n)O(\log n)O(log⁡n)O(\log n)sorted iteration; begin() is the minimum
unordered_map / unordered_sethash table with bucketsO(1)O(1) average, O(n)O(n) worstO(1)O(1) averageno order; rehashing on growth
priority_queuebinary heap on a vectortop O(1)O(1)push and pop O(log⁡n)O(\log n)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:

ContainerInsertErase
vectorif the size exceeds capacity (reallocation): all invalidated; otherwise those at or after the insertion pointthose at or after the erased element
dequeat either end: all iterators invalidated, but references and pointers stay valid; in the middle: allat either end: only the erased elements (plus end() at the back); in the middle: all
list, map, setnoneonly the erased element
unordered_map / setif it causes a rehash: all iterators, but references and pointers stay valid; otherwise noneonly 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: O(nlog⁡n)O(n \log n), not stable (introsort). std::stable_sort keeps the order of equal elements. Both need random-access iterators, so a std::list uses its member sort().
  • std::lower_bound returns the first element not less than the value; std::upper_bound the first element greater than it; both are O(log⁡n)O(\log n) on a sorted random-access range. upper_bound - lower_bound counts the copies of a value. On a std::map, call the member m.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 of init. With 0 instead of 0.0, every partial sum is truncated to int.
  • Erase-remove: std::remove_if moves the kept elements to the front and returns the new logical end; erase then trims the tail. One O(n)O(n) pass instead of O(n2)O(n^2) repeated erases.
  • Also worth knowing: std::find_if, std::count_if, std::min_element/std::max_element, std::nth_element (average O(n)O(n) selection, for medians and percentiles), std::partial_sort (top kk), and std::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, 0+0.50 + 0.5 is truncated back to 00 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 tt (an "as-of" join, used to mark trades to the prevailing mid), or nullptr if tt is earlier than every quote. It must be O(log⁡n)O(\log n).

Show 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 tt. 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: t=100t = 100 and t=400t = 400 land exactly on a quote and must return it (so upper_bound, not lower_bound, which would need a separate equality check), and t=5000t = 5000 returns the last quote. Each lookup is one binary search, O(log⁡n)O(\log n). 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 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 O(log⁡L)O(\log L) insert, find and erase over LL 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 O(1)O(1) 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 (O(1)O(1) 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

  • vector is the default; map/set for sorted data with O(log⁡n)O(\log n) updates; unordered_map for O(1)O(1) average lookup without order; deque for both ends; list only when you need stable positions and O(1)O(1) splicing.
  • Vector reallocation invalidates everything; node-based containers never move their elements. Erase while iterating with it = c.erase(it) or std::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).