Kodewick
Start learning →
What STL operations cost4 / 52

What STL operations cost

Lesson 4 of 52 · Part 1 · Getting started: how fast · about 24 minutes

STL operations hide costs: push_back on a vector is O(1) on average, but insert at the front moves every element; set and map take about log n comparisons, and unordered_map looks in one bucket.

A logging program puts every new message at the front of a vector with v.insert(v.begin(), msg), so the newest comes first. It is fast at first; after a day of 100 000 messages, every insert moves all the earlier ones back one place, and the 100 000 inserts make 5 billion moves. Change the vector to a deque and insert to push_front, and nothing moves at all. Every STL operation has a cost; this lesson counts the most common ones one by one, then gathers them in a cheat sheet.

vector: fast at the end

A vector is one contiguous array plus two numbers: size() is how many it holds, capacity() how many cells the array has. On push_back, if there is a free cell it goes straight in, O(1). If not, the vector gets a new array twice as big, moves all the old elements over, then adds the new one. Count the moves:

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> v;7    size_t cap = v.capacity();8    int grows = 0;9    long long copied = 0;10    cout << "capacity: ";11    for (int i = 0; i < 1000; i++) {12        if (v.size() == v.capacity())13            copied += v.size();          // full: all of these must move14        v.push_back(i);15        if (v.capacity() != cap) {16            cap = v.capacity();17            grows++;18            cout << cap << " ";19        }20    }21    cout << "\nafter 1000 elements: " << grows << " new arrays, " << copied << " elements moved\n";22    return 0;23}
Output
capacity: 1 2 4 8 16 32 64 128 256 512 1024 
after 1000 elements: 11 new arrays, 1023 elements moved

The moves get rarer and rarer: 1 + 2 + 4 + … + 512 = 1023, fewer than n. On average each element is moved once or twice at most, which is why push_back is amortised O(1): now and then one call is expensive (O(n)), but spread over all the calls it is still a fixed number each.

Guess the outputA wrong guess is fine

After 5 elements, what are size and capacity (with g++)?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> v;7    for (int i = 0; i < 5; i++)8        v.push_back(i);9    cout << v.size() << " " << v.capacity() << "\n";10    return 0;11}
Choose one

A vector holds 1000 elements and size() == capacity(). You push_back one more. How much work does this one call do?

vector, inserting at the front: everything moves back

push_back at the end is fast; inserting at the front of a vector is slow. The new element must go in cell 0, so every old element moves back one place, starting with the last:

v (size = 4, capacity = 5)246801234↑i
1for (int i = n; i > 0; i--)2    v[i] = v[i - 1];3v[0] = x;

What v.insert(v.begin(), 1) does inside: 4 elements each move back one place, from the last, and cell 0 is free

In C++ the elements can count for themselves: give them a copy constructor and an assignment operator that add one every time they are copied (moved along). Compare adding at the end and at the front with such an Item:

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5long long moves = 0;6 7struct Item {8    int v;9    Item(int x) : v(x) {}10    Item(const Item& o) : v(o.v) { moves++; }                  // one copy, one count11    Item& operator=(const Item& o) { v = o.v; moves++; return *this; }12};13 14int main() {15    int sizes[] = {10, 100, 1000};16    for (int n : sizes) {17        vector<Item> back, front;18        moves = 0;19        for (int i = 0; i < n; i++)20            back.push_back(Item(i));21        long long at_back = moves;22        moves = 0;23        for (int i = 0; i < n; i++)24            front.insert(front.begin(), Item(i));25        cout << "n = " << n << "  push_back copies " << at_back << ", insert at the front copies " << moves << "\n";26    }27    return 0;28}
Output
n = 10  push_back copies 25, insert at the front copies 55
n = 100  push_back copies 227, insert at the front copies 5050
n = 1000  push_back copies 2023, insert at the front copies 500500

1000 push_backs made 2023 copies: 1 to put each one in, plus the 1023 moves when the array grew, about 2n. 1000 inserts at the front made 500 500: the k-th moves the k − 1 before it and then puts itself in, 1 + 2 + … + 1000 = n(n + 1)/2, O(n²) in all, O(n) each. erase(v.begin()) is the same: everything behind moves forward.

OperationElements movedCost
v[i], v.back(), v.size()0O(1)
v.push_back(x), v.pop_back()0 (now and then a move to a new array)amortised O(1)
v.insert(v.begin(), x), v.erase(v.begin())all nO(n)
v.insert(v.begin() + i, x)the n − i after iO(n − i)
Choose one

v holds 10 elements. How many of them does v.insert(v.begin() + 3, x) move back?

deque and list: nothing moves

A deque (double-ended queue, <deque>) keeps its elements in fixed-size blocks, plus a table of those blocks. Adding at the front uses a free cell in the first block, or adds a new block in front: nothing moves. Indexing d[i] works out which block and which cell, also O(1).

A list (<list>) is a doubly linked list: each element is its own node that knows the one before and the one after. Given a position (an iterator), inserting or erasing there changes a few pointers, O(1). The price is no indexing: to get the i-th you walk from the start, O(i).

main.cpp
1#include <iostream>2#include <vector>3#include <deque>4#include <list>5using namespace std;6 7long long moves = 0;8 9struct Item {10    int v;11    Item(int x) : v(x) {}12    Item(const Item& o) : v(o.v) { moves++; }13    Item& operator=(const Item& o) { v = o.v; moves++; return *this; }14};15 16template <class C>17long long front_inserts(int n) {        // insert at the front n times, count the copies18    C c;19    moves = 0;20    for (int i = 0; i < n; i++)21        c.insert(c.begin(), Item(i));22    return moves;23}24 25int main() {26    deque<int> d;27    for (int i = 1; i <= 3; i++) {28        d.push_front(i);29        d.push_back(i * 10);30    }31    for (int x : d) cout << x << " ";32    cout << "  d[4] = " << d[4] << "\n";33 34    list<int> l = {1, 2, 4};35    auto it = next(l.begin(), 2);       // walk 2 steps from the start, to the 4: O(i)36    l.insert(it, 3);                    // put 3 before the 4: O(1)37    for (int x : l) cout << x << " ";38    cout << "\n";39 40    cout << "1000 inserts at the front: vector copies " << front_inserts<vector<Item>>(1000)41         << ", deque " << front_inserts<deque<Item>>(1000)42         << ", list " << front_inserts<list<Item>>(1000) << "\n";43    return 0;44}
Output
3 2 1 10 20 30   d[4] = 20
1 2 3 4 
1000 inserts at the front: vector copies 500500, deque 1000, list 1000
vectorv.insert(v.begin(), x)500 500 copiesmoves them all each time: O(n)
dequed.push_front(x)1 000 copiesonly itself: O(1)
listl.push_front(x)1 000 copiesa few pointers: O(1)
1000 inserts at the front: how many times elements are copied (counted by the program in this level)

If a deque is fast at both ends and can be indexed, why not use it everywhere? Because it comes in blocks: d[i] has an extra step, and walking through it is a little slower than through a contiguous vector; inserting in the middle still moves elements, O(n). A list news every node separately and stores two extra pointers, and walking it jumps around in memory. Use vector by default, a deque when things go in or out at the front, and a list only for frequent inserts and erases in the middle when you already hold the position.

Choose one

A program keeps adding new elements at the front and also often reads the i-th one by index. Which container?

Guess the outputA wrong guess is fine

Two numbers go into a list. What does it print?

1#include <iostream>2#include <list>3using namespace std;4 5int main() {6    list<int> l = {10, 20, 30, 40};7    auto it = next(l.begin(), 3);8    l.insert(it, 35);9    l.push_front(5);10    for (int x : l) cout << x << " ";11    cout << "\n";12    return 0;13}

Counting comparisons: set, map, priority_queue

Inside set and map (<set>, <map>) is a red-black tree: a binary search tree that keeps itself balanced, always within 2 log₂(n + 1) levels. Insert, find and erase all walk one path down from the root, one comparison per level: O(log n). A priority_queue (<queue>) is a binary heap kept in a vector: push floats up from the bottom, pop puts the last element on top and sinks it down, each along one path from top to bottom: O(log n).

They all work by comparing, and their comparison is a template argument. Pass one that counts:

main.cpp
1#include <iostream>2#include <vector>3#include <set>4#include <queue>5using namespace std;6 7long long cmps = 0;8 9struct Less {10    bool operator()(int a, int b) const {11        cmps++;                          // one comparison, one count12        return a < b;13    }14};15 16int main() {17    vector<int> a(1000);18    unsigned seed = 1;19    for (int i = 0; i < 1000; i++) {20        seed = seed * 1103515245 + 12345;21        a[i] = (seed >> 16) % 10000;     // 1000 shuffled numbers22    }23 24    set<int, Less> s;25    cmps = 0;26    for (int x : a) s.insert(x);27    cout << "set, 1000 inserts: " << cmps << " comparisons (with repeats, " << s.size() << " left)\n";28    cmps = 0;29    for (int x : a) s.find(x);30    cout << "set, 1000 finds: " << cmps << " comparisons\n";31 32    priority_queue<int, vector<int>, Less> pq;33    cmps = 0;34    for (int x : a) pq.push(x);35    cout << "priority_queue, 1000 pushes: " << cmps << " comparisons\n";36    cmps = 0;37    while (!pq.empty()) pq.pop();38    cout << "priority_queue, 1000 pops: " << cmps << " comparisons\n";39    return 0;40}
Output
set, 1000 inserts: 10622 comparisons (with repeats, 940 left)
set, 1000 finds: 11086 comparisons
priority_queue, 1000 pushes: 2191 comparisons
priority_queue, 1000 pops: 8673 comparisons

log₂ 1000 ≈ 10. Each set insert or find makes 10 to 11 comparisons: log n. Each pop makes 8 to 9, sinking level by level. A push averages only just over 2: in the worst case it floats up log n levels, but with shuffled data it usually stops after one or two, so we only say O(log n) in the worst case. map is the same tree with a value hung on each node: m[key] and m.find(key) are O(log n) too.

Guess the outputA wrong guess is fine

Four numbers go in, then one pop. What does it print?

1#include <iostream>2#include <queue>3using namespace std;4 5int main() {6    priority_queue<int> pq;7    for (int x : {4, 9, 2, 7})8        pq.push(x);9    pq.pop();10    cout << pq.top() << " " << pq.size() << "\n";11    return 0;12}

sort: n log n comparisons

Sorting works by comparing too. sort (<algorithm>) in g++ is introsort: mostly quicksort, switching to heap sort when the splits go badly, and insertion sort for the last short stretches. It makes on the order of n log n comparisons. Compare it with "every pair once", n(n − 1)/2:

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6long long cmps = 0;7 8struct Less {9    bool operator()(int a, int b) const { cmps++; return a < b; }10};11 12int main() {13    vector<int> a(1000);14    unsigned seed = 1;15    for (int i = 0; i < 1000; i++) {16        seed = seed * 1103515245 + 12345;17        a[i] = (seed >> 16) % 10000;18    }19    int sizes[] = {10, 100, 1000};20    for (int n : sizes) {21        vector<int> b(a.begin(), a.begin() + n);22        cmps = 0;23        sort(b.begin(), b.end(), Less());24        cout << "n = " << n << "  sort compares " << cmps << " times, every pair would be " << n * (n - 1) / 2 << "\n";25    }26    return 0;27}
Output
n = 10  sort compares 36 times, every pair would be 45
n = 100  sort compares 840 times, every pair would be 4950
n = 1000  sort compares 12230 times, every pair would be 499500

For n = 1000, sort makes just over ten thousand comparisons (n log₂ n ≈ 10 000); every pair would be half a million. The bigger n, the bigger the gap: for n = a million, one is about 20 million, the other 500 billion.

Choose one

You sort n numbers once, then look up n numbers with lower_bound. What is the whole thing?

unordered_map: work out the bucket, look in one place

unordered_map and unordered_set (<unordered_map>, <unordered_set>) don't compare sizes. They keep a row of buckets; to put a key in they work out hash(key) % bucket count and add it to that bucket's chain; to look a key up they work it out again and search only that bucket. In g++ the hash of an int is the int itself, so with 13 buckets 10, 23 and 36 all land in bucket 10:

key % 130123456789101112

13 buckets; put in 10, 23, 5, 12, 36 (key % 13), then look for 36: only bucket 10 is searched

The more a bucket holds, the more comparisons a lookup needs, so the table keeps at least as many buckets as elements (load_factor() = elements / buckets; past 1 it grows): it takes a row of a little over twice as many buckets (g++ uses primes) and puts every element in again. Like the vector's doubling, it is O(n) now and then and O(1) amortised:

main.cpp
1#include <iostream>2#include <unordered_map>3using namespace std;4 5int main() {6    unordered_map<int, int> m;7    size_t buckets = m.bucket_count();8    cout << "buckets: " << buckets;9    for (int i = 0; i < 1000; i++) {10        m[i * 7] = i;11        if (m.bucket_count() != buckets) {12            buckets = m.bucket_count();13            cout << " → " << buckets;14        }15    }16    cout << "\n" << m.size() << " keys, " << m.bucket_count() << " buckets, load_factor = " << m.load_factor() << "\n";17    cout << "m.count(700) = " << m.count(700) << ", m[700] = " << m[700] << "\n";18    return 0;19}
Output
buckets: 1 → 13 → 29 → 59 → 127 → 257 → 541 → 1109
1000 keys, 1109 buckets, load_factor = 0.901713
m.count(700) = 1, m[700] = 100

So insert, find, count and m[key] are all O(1) on average. "On average", because when many keys happen to crowd into one bucket, that bucket is searched one by one, O(n) in the worst case. Two more differences from map: there is no order inside (iterating gives bucket order, which changes with the compiler, so don't print by it); and there is no lower_bound: for "the first ≥ x" you need a map or set.

Choose one

7 buckets; each key goes in bucket key % 7. After putting in 3, 10, 17 and 5, which bucket is 17 in, and how many keys are in that bucket?

Guess the outputA wrong guess is fine

Both count and m[key] can look up a key. What does it print?

1#include <iostream>2#include <unordered_map>3using namespace std;4 5int main() {6    unordered_map<int, int> m;7    m[3] = 30;8    int a = m.count(7);9    int b = m[7];10    cout << a << " " << b << " " << m.size() << "\n";11    return 0;12}
Exercise 1

Two sum

Find two numbers in nums that add up to target and return their indexes {i, j} with i < j, or {-1, -1} if there are none. Two nested loops are O(n²); remember "value → index" in an unordered_map and one pass is enough: at nums[j], check whether target - nums[j] has been seen.

It should print
0 1
1 2
-1 -1
exercise1.cpp
1#include <iostream>2#include <vector>3#include <unordered_map>4#include <utility>5using namespace std;6 7pair<int, int> two_sum(const vector<int>& nums, int target) {8    unordered_map<int, int> where;       // value -> its index9    for (int j = 0; j < (int)nums.size(); j++) {10        // is target - nums[j] in where? then remember nums[j]11    }12    return {-1, -1};13}14 15int main() {16    pair<int, int> p = two_sum({2, 7, 11, 15}, 9);17    cout << p.first << " " << p.second << "\n";18    p = two_sum({3, 2, 4}, 6);19    cout << p.first << " " << p.second << "\n";20    p = two_sum({1, 2}, 7);21    cout << p.first << " " << p.second << "\n";22    return 0;23}
Output
Press Run or Ctrl+Enter

With the STL

Everything counted in this lesson in one place. The lit rows are "one line, one loop": think twice before putting them in a loop:

ContainerOperationCost
vectorv[i], push_back, pop_back, backO(1) (push_back amortised)
vectorinsert(v.begin(), x), erase(v.begin())O(n)
vectorfind(b, e, x), count(b, e, x)O(n)
dequepush_front, push_back, pop_front, d[i]O(1)
listinsert, erase at an iteratorO(1)
listgetting to the i-th: next(l.begin(), i)O(i)
set / mapinsert, erase, find, count, m[k], lower_boundO(log n)
unordered_set / mapinsert, erase, find, count, m[k]O(1) average, O(n) worst
priority_queuepush, pop; topO(log n); O(1)
algorithmsort(b, e)O(n log n)
algorithmlower_bound(b, e, x) once sortedO(log n)
The cost of common STL operations (n is the number of elements)

Two easy wins: if you know how many elements are coming, reserve first. A vector's reserve(n) gets n cells at once and never moves again; an unordered_map's reserve(n) gets enough buckets for n keys at once and never re-places them:

main.cpp
1#include <iostream>2#include <vector>3#include <unordered_map>4using namespace std;5 6long long moves = 0;7 8struct Item {9    int v;10    Item(int x) : v(x) {}11    Item(const Item& o) : v(o.v) { moves++; }12    Item& operator=(const Item& o) { v = o.v; moves++; return *this; }13};14 15int main() {16    vector<Item> v;17    v.reserve(1000);                    // 1000 cells at once18    for (int i = 0; i < 1000; i++)19        v.push_back(Item(i));20    cout << "1000 push_backs after reserve: " << moves << " copies\n";21 22    unordered_map<int, int> m;23    m.reserve(1000);                    // buckets for 1000 keys at once24    size_t before = m.bucket_count();25    for (int i = 0; i < 1000; i++)26        m[i * 7] = i;27    cout << "buckets " << before << " → " << m.bucket_count() << ", it never grew\n";28    return 0;29}
Output
1000 push_backs after reserve: 1000 copies
buckets 1031 → 1031, it never grew

Without reserve it took 2023 copies; now exactly 1000: each element is put in once.

In interviews: when asked for the complexity of your code, the usual slip is missing these lines: a v.insert(v.begin(), x), v.erase(v.begin()) or find inside a loop multiplies the complexity by n. The other way round, swapping a vector for a deque, find for an unordered_set, or sorting once and then using lower_bound, is often exactly the improvement the interviewer is waiting for. Asked "map or unordered_map?": if you need order or lower_bound, map (O(log n)); if you only check membership and look up by key, unordered_map (O(1) on average).

Choose one

Which line, put inside a loop that runs n times, makes the whole thing O(n²)? (v is a vector, d a deque, u an unordered_set)

Exercise 2

Remove repeats, keep the order

dedupe(items) removes repeats, keeping the first time each value appears, in the original order. Checking with find(result.begin(), result.end(), x) in the vector also works, but it is O(n²) for n elements. Remember what you've seen in an unordered_set to make it O(n) on average.

It should print
3 1 2 5
exercise2.cpp
1#include <iostream>2#include <vector>3#include <unordered_set>4using namespace std;5 6vector<int> dedupe(const vector<int>& items) {7    unordered_set<int> seen;8    vector<int> result;9    for (int x : items) {10        // not seen before: add it to seen and to result11    }12    return result;13}14 15int main() {16    vector<int> r = dedupe({3, 1, 3, 3, 2, 1, 5});17    for (int x : r) cout << x << " ";18    cout << "\n";19    return 0;20}
Output
Press Run or Ctrl+Enter

Summary

Take-away

Every container operation has a cost

  • vector: push_back at the end is amortised O(1); insert / erase at the front moves everything, O(n)
  • deque is O(1) at both ends; list inserts and erases at an iterator in O(1), but has no indexing
  • set / map and priority_queue: O(log n); sort: O(n log n)
  • unordered_map / unordered_set: O(1) on average, no order
1v.reserve(n);                // enough capacity up front, no more moving2d.push_front(x);             // deque: O(1)3s.count(x);                  // set O(log n), unordered_set O(1) on average4sort(a.begin(), a.end());    // O(n log n)