Arrays that grow: vector
A dynamic array lives on the heap and, when full, moves to a block twice the size (new[], copy, delete[]), so adding at the end is O(1) on average; vector works this way, its capacity doubling.
The array list in the last lesson holds at most MAX elements; when it's full, nothing more goes in. A real program doesn't know beforehand how many it will hold. The fix is to put the array on the heap: new[] a small block first, and when it's full, swap it for a bigger one and copy the old elements over. That is what a vector does underneath. This lesson writes one by hand, then looks at vector's size and capacity.
A block on the heap
1class Vec {2 int* data = nullptr; // points at a block on the heap3 int len = 0; // how many are in it4 int cap = 0; // how many this block can hold5};
len is how many slots are in use, cap how many there are. len == cap means full.
Start with new int[4], a block for 4 ints: data = new int[4];, so cap = 4 and len = 0. Unlike C's malloc, new[] asks for a number of elements, so there's no sizeof(int) to multiply by. The block on the heap doesn't vanish when a function returns; when you're done, give it back with delete[] data.
stack
v.dataint*v.lenint2v.capint4heap
How do you give back the block from data = new int[4]; when you're done?
new[] gives you goes back with delete[] (with the brackets); new pairs with delete, and malloc with free. Don't mix them. Nothing on the heap goes back by itself: forget it and you leak memory.What does this program print?
1#include <iostream>2using namespace std;3 4int main() {5 int* data = new int[4];6 int len = 0, cap = 4;7 for (int i = 1; i <= 3; i++)8 data[len++] = i * 10;9 cout << len << " " << cap << " " << data[len - 1] << "\n";10 delete[] data;11 return 0;12}
data[len++] = x puts x in data[len] and then adds 1 to len, so the last one is in data[2]: 30.Full: swap for a block twice the size
C has realloc to "make a block bigger"; in C++ you do three steps yourself: new int[new size] gets a new block, the old elements are copied over one by one, delete[] gives the old block back, and data is pointed at the new one.
stack
v.dataint*biggerint*heap
1int* bigger = new int[new_cap];2for (int i = 0; i < len; i++)3 bigger[i] = data[i];4delete[] data;5data = bigger;6cap = new_cap;
1#include <iostream>2using namespace std;3 4class Vec {5public:6 ~Vec() { delete[] data; } // give it back when done7 8 void push(int x) {9 if (len == cap) {10 int new_cap = cap ? cap * 2 : 1; // double each time11 int* bigger = new int[new_cap];12 for (int i = 0; i < len; i++)13 bigger[i] = data[i];14 delete[] data; // delete[] nullptr does nothing15 cout << " new block: room for " << cap << " → " << new_cap << "\n";16 data = bigger;17 cap = new_cap;18 }19 data[len++] = x;20 }21 int& operator[](int i) { return data[i]; }22 int size() const { return len; }23 int capacity() const { return cap; }24 25private:26 int* data = nullptr;27 int len = 0;28 int cap = 0;29};30 31int main() {32 Vec v;33 for (int i = 1; i <= 10; i++)34 v.push(i * 10);35 cout << "len = " << v.size() << ", cap = " << v.capacity()36 << ", last = " << v[v.size() - 1] << "\n";37 return 0;38}
new block: room for 0 → 1 new block: room for 1 → 2 new block: room for 2 → 4 new block: room for 4 → 8 new block: room for 8 → 16 len = 10, cap = 16, last = 100
What new[] gives goes back with delete[] (with the brackets); it's in the destructor, so it happens by itself when v leaves main. operator[] lets you write v[i] as for an array; it returns int&, so v[0] = 5 changes the element inside. (Don't copy a Vec: two Vecs would delete[] the same block.)
Starting from cap = 0 (the first block has 1 slot) and doubling every time it fills up, what is cap after 20 pushes?
Write the growing
✓Finish grow: new[] a block of new_cap, copy the len elements over, delete[] the old one, and set data and cap. Make the program print the line below.
len = 5, cap = 8
1#include <iostream>2using namespace std;3 4class Vec {5public:6 ~Vec() { delete[] data; }7 8 void push(int x) {9 if (len == cap)10 grow();11 if (len < cap) // only if it fits12 data[len++] = x;13 }14 int size() const { return len; }15 int capacity() const { return cap; }16 17private:18 void grow() {19 int new_cap = cap ? cap * 2 : 1;20 // new[] a block of new_cap, copy, delete[] the old one, set data and cap21 }22 23 int* data = nullptr;24 int len = 0;25 int cap = 0;26};27 28int main() {29 Vec v;30 for (int i = 1; i <= 5; i++)31 v.push(i);32 cout << "len = " << v.size() << ", cap = " << v.capacity() << "\n";33 return 0;34}
After the swap, old addresses are no good
Two orders to remember. First, copy, then delete[]: the other way round, the copying reads memory that has already been given back. Second, after the swap every pointer and reference you kept into the old block dangles:
stack
v.dataint*pint*heap
A vector is the same: once push_back has swapped its block, the &v[0], int& r = v[0] and iterators you had can't be used. Indexes are fine: "which one" has nothing to do with which block the elements are in.
You save int* old = data;, then a push swaps blocks: the old block is delete[]d and data points at the new one. What about old?
data; it doesn't touch any other variable. old still holds the old address, and that block has been given back. This is a dangling pointer. After a swap, take data or &v[0] again.Put the 4 lines of the grow in order: 2 cells are full, swap to 4, then add 9, and the program prints 7 8 9 4.
delete[] data;data = bigger;for (int i = 0; i < len; i++) bigger[i] = data[i];int* bigger = new int[cap * 2];
7 8 9 4
new[] a new block, then copy, only then delete[] the old one, and finally point data at the new block. delete[] first and copy after, and you're reading memory that has been given back: the engine here stops at that line with an error.Why doubling
| How it grows when full | Copies to put in n | Average per element |
|---|---|---|
| one more slot | about n²/2 | O(n) |
| double | fewer than n | O(1) (amortised) |
One push on its own (say the 9th, which copies 8) is O(n), but those get rarer and rarer, and on average each push is a constant: that is amortised O(1). The price of doubling is some empty slots (at most half). A little space for time: that is the choice most languages' dynamic arrays make.
Starting from 1 slot and doubling each time, how many copies does putting in 16 numbers take?
1#include <iostream>2using namespace std;3 4int main() {5 int cap = 1, copies = 0;6 for (int len = 0; len < 16; len++) {7 if (len == cap) {8 copies += len; // a new block: copy all len elements over9 cap *= 2;10 }11 }12 cout << copies << "\n";13 return 0;14}
What if, when full, you only added 10 slots (cap += 10)? Pushing n values, what does each push cost on average?
Start at 1 slot, double every time it fills up, and push 17 values in all. What is cap now, and how many slots are empty?
With the STL
vector<int> is the Vec this lesson wrote by hand: one contiguous block on the heap, keeping how many slots are used and how many there are.
v.size(): how many are in it (len).v.capacity(): how many fit without swapping blocks (cap).- When
push_backhas no room, g++'svectorgets a block twice the size, moves the old elements over and gives the old block back.
Print capacity() each time it changes:
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> v;7 size_t old = v.capacity();8 cout << "empty: size " << v.size() << ", capacity " << old << "\n";9 for (int i = 1; i <= 20; i++) {10 v.push_back(i);11 if (v.capacity() != old) {12 cout << "new block at element " << i << ": capacity " << old << " → " << v.capacity() << "\n";13 old = v.capacity();14 }15 }16 cout << "size " << v.size() << ", capacity " << v.capacity() << "\n";17 18 vector<int> w;19 w.reserve(20); // get 20 slots at once20 for (int i = 1; i <= 20; i++)21 w.push_back(i);22 cout << "after reserve: size " << w.size() << ", capacity " << w.capacity() << "\n";23 24 w.clear(); // the elements are gone, the block stays25 cout << "after clear: size " << w.size() << ", capacity " << w.capacity() << "\n";26 return 0;27}
empty: size 0, capacity 0 new block at element 1: capacity 0 → 1 new block at element 2: capacity 1 → 2 new block at element 3: capacity 2 → 4 new block at element 5: capacity 4 → 8 new block at element 9: capacity 8 → 16 new block at element 17: capacity 16 → 32 size 20, capacity 32 after reserve: size 20, capacity 20 after clear: size 0, capacity 20
The capacity goes 1, 2, 4, 8, 16, 32: it doubles each time there's no room, and 20 elements took only 6 new blocks. If you know roughly how many there will be, reserve(n) first gets enough at once, with no swapping on the way. clear() removes the elements but keeps the memory.
| operation | cost |
|---|---|
v[i], v.size(), v.capacity() | O(1) |
push_back(x) | amortised O(1); O(n) on the push that swaps blocks |
pop_back() | O(1), capacity doesn't shrink |
reserve(n) | O(n) once (if it swaps), then no more swaps up to n |
clear() | O(n) (destroys each element), capacity unchanged |
Doubling is what g++ does; the C++ standard only asks for push_back to be amortised O(1), and Microsoft's compiler multiplies by 1.5. Don't let a program depend on the exact capacity.
In interviews: "Why is vector's push_back O(1)": say amortised: one growth is O(n), but growing in proportion means n push_backs move fewer than 2n elements in all. The follow-up "why not +100 each time": a fixed step moves O(n²) in all. "What happens after it grows": the elements move to a new address, and every earlier pointer, reference and iterator is invalid. If you know the size, reserve first.
How many blocks did vector take
✓push_back 1 to 100 into an empty v. After each push_back, a changed capacity() means a new block. Count them, then print the count and the capacity.
new blocks: 8, capacity = 128
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> v;7 int changes = 0;8 for (int i = 1; i <= 100; i++) {9 // note the capacity before push_back, compare after10 v.push_back(i);11 }12 cout << "new blocks: " << changes << ", capacity = " << v.capacity() << "\n";13 return 0;14}
First reserve(10), push 3, then clear(). What does it print?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> v;7 v.reserve(10);8 for (int i = 0; i < 3; i++)9 v.push_back(i);10 v.clear();11 cout << v.size() << " " << v.capacity() << "\n";12 return 0;13}
reserve(10) gets 10 cells at once, so 3 pushes need no swap. clear() only removes the elements: size becomes 0, but the block stays, so capacity is still 10.Summary
Dynamic arrays: when full, swap for a block twice the size
- len / size is the slots in use, cap / capacity the slots there are
- the swap: new[] a new block, copy, delete[] the old one, point at the new one
- after the swap, old pointers, references and iterators dangle
- doubling: push is amortised O(1); g++'s vector doubles too, and reserve gets enough at once
1int* bigger = new int[cap * 2];2for (int i = 0; i < len; i++) bigger[i] = data[i];3delete[] data;4data = bigger; cap *= 2;5v.reserve(n); // vector: get n slots first