Arrays and Vectors

Lesson 3 of 20

Watch a vector erase shift seven boxes left, then fill an int array in 3D memory one write at a time.

The big picture

The big picture

Arrays and vectors are the workhorses of DSA: a fixed block you index instantly, and its growable cousin.

Contiguous memory

Elements sit side by side, so a[i] is one address calculation: start + i * sizeof(int). That is why indexing is O(1).

Array vs vector

int a[5] is fixed at compile time. vector<int> v grows at runtime by doubling its capacity — amortized O(1) per push_back.

Middle ops cost O(n)

Insert or erase anywhere except the end and every later element slides one slot — the animation below shows the shift.

Iterator invalidation

When push_back reallocates, the block moves — old iterators and pointers point at freed memory.

Range-for

for (int x : v) visits every element without index math — the safest way to read a vector.