Arrays and vector: straight to an index
A C++ array or vector stores its elements one after another, so the address of a[i] is the start plus i elements, one step away; v[i] doesn't check the bounds, while v.at(i) throws an exception.
a[0] or a[999999]: which is faster to get? Neither. This lesson shows why: a C++ array is one block of memory, one element after another, so where element i is can be worked out, not searched for. A vector is laid out the same way, so v[i] is one step too.
One after another
int a[5] = {10, 20, 30, 40, 50}; is five ints side by side in memory. An int takes 4 bytes, so each next one is 4 further on.
stack
a[0]int10a[1]int20a[2]int30a[3]int40a[4]int50(The addresses are an example: the real ones may change every run, but "4 apart" doesn't.)
In int a[5], a[0] is at address 2000, and an int takes 4 bytes. Where is a[1]?
sizeof measures how many bytes something takes. What does this program print?
1#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {10, 20, 30, 40, 50};6 cout << sizeof(a) << "\n";7 return 0;8}
sizeof(a) / sizeof(a[0]) is 5.Working out the address
The elements sit side by side and are all the same size, so you never have to search for element i. Its address is simply:
address of a[i] = address of a + i × the size of one element
One multiplication and one addition, whatever i is and however long the array: getting an element by index is O(1). It is also why indexes start at 0: the first element is 0 elements from the start.
We don't print the addresses themselves (they change between runs), only how far apart they are. Cast to char* and subtract, and you get bytes; subtract directly, and you get elements:
1#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {10, 20, 30, 40, 50};6 // how many bytes apart two addresses are7 cout << "a[1] is " << (char*)&a[1] - (char*)&a[0] << " bytes after a[0]\n";8 cout << "a[3] is " << (char*)&a[3] - (char*)&a[0] << " bytes after a[0]\n";9 cout << "an int takes " << sizeof(int) << " bytes\n";10 // without char*: how many elements apart11 cout << "&a[3] - &a[0] = " << &a[3] - &a[0] << "\n";12 return 0;13}
a[1] is 4 bytes after a[0] a[3] is 12 bytes after a[0] an int takes 4 bytes &a[3] - &a[0] = 3
A double takes 8 bytes. How many bytes after &d[0] is &d[4]?
1#include <iostream>2using namespace std;3 4int main() {5 double d[10];6 cout << (char*)&d[4] - (char*)&d[0] << "\n";7 return 0;8}
Pointers work it out the same way
a[i] is really *(a + i): used as a pointer, an array's name is the address of its first element, and + i multiplies by the element's size for you.
1#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {10, 20, 30, 40, 50};6 int* p = a; // points at a[0]7 cout << a[3] << " " << *(p + 3) << "\n";8 p = p + 2; // two ints further on9 cout << *p << " " << p[1] << "\n";10 return 0;11}
40 40 30 40
p[1] is *(p + 1): one further on from where p points, which is 40.
p points at a[1]. What does this program print?
1#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {10, 20, 30, 40, 50};6 int* p = a + 1;7 cout << *p << " " << p[2] << "\n";8 return 0;9}
*p is what p points at, a[1], which is 20. p[2] is *(p + 2): 2 further on from a[1], so a[3] = 40. Indexes count from wherever the pointer points.Fill in a number so the program prints 30.
1#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {10, 20, 30, 40, 50};6 cout << *(a + ) << "\n";7 return 0;8}
a[2] is *(a + 2). a + 2 moves on 2 ints; the compiler multiplies by the 4 bytes itself.Print it backwards
✓Using *(a + i), print the array backwards, from the last element to the first.
50 40 30 20 10
1#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {10, 20, 30, 40, 50};6 // i goes from 4 down to 0, print *(a + i)7 cout << "\n";8 return 0;9}
2-D arrays: one row after another
int m[2][3] is a table of 2 rows and 3 columns. But memory has no rows or columns, just one long strip, so C++ lays the table out row after row: first the 3 values of row 0, then straight after them the 3 of row 1. This is called row-major order.
stack
m[0][0]int1m[0][1]int2m[0][2]int3m[1][0]int4m[1][1]int5m[1][2]int6So to reach m[i][j], skip i whole rows (3 values each), then j more:
address of m[i][j] = start + (i × number of columns + j) × element size
Just like a 1-D array, it is one calculation away: still O(1). Exams love this one. Watch out: you multiply by the number of columns.
1#include <iostream>2using namespace std;3 4int main() {5 int m[2][3] = {{1, 2, 3}, {4, 5, 6}};6 cout << (char*)&m[1][0] - (char*)&m[0][0] << "\n";7 cout << (char*)&m[1][2] - (char*)&m[0][0] << "\n";8 return 0;9}
12 20
m[1][0] has 1 × 3 + 0 = 3 ints before it, so it is 12 bytes on; m[1][2] has 1 × 3 + 2 = 5 before it, so 20 bytes on.
int m[3][4] has 3 rows and 4 columns; an int takes 4 bytes. How many bytes after &m[0][0] is &m[2][1]?
1#include <iostream>2using namespace std;3 4int main() {5 int m[3][4];6 cout << (char*)&m[2][1] - (char*)&m[0][0] << "\n";7 return 0;8}
int m[4][5] is stored row by row from address 1000, and an int takes 4 bytes. What is the address of m[3][2]?
Past the end: nobody stops you
int a[5] has a[0] to a[4]. Write a[5] and the address still works out, but that memory isn't the array's: reading it gets something else, and writing it breaks another variable. C++ arrays don't check indexes, and neither does a vector's v[i].
stack
a[3]int40a[4]int50sumint1501#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {10, 20, 30, 40, 50};6 int sum = 0;7 for (int i = 0; i <= 5; i++) // one step too far8 sum += a[i];9 cout << sum << "\n";10 return 0;11}
index 5 out of bounds for type 'int [5]'What happened: Stopped at line 8. This goes past the end of a vector, an array or a string. Real C++ would read or overwrite whatever is next in memory.
Press Run and see what happens. Our C++ stops right there and says which element was out of bounds; real g++ doesn't stop and works out some unpredictable number. The usual mistake is i <= n; it should be i < n.
int a[5]; Which of these loops goes past the end?
a[5] is not part of the array: the valid indexes are 0 to 4. This loop also skips a[0].This loop goes one step too far. Change only the number in the green box so it adds exactly the 5 elements and prints 150.
1#include <iostream>2using namespace std;3 4int main() {5 int a[5] = {10, 20, 30, 40, 50};6 int sum = 0;7 for (int i = 0; i <= ; i++)8 sum += a[i];9 cout << sum << "\n";10 return 0;11}
150
i <= 4, which is the same as the usual i < 5.Add them up
✓Finish the loop: add up the 6 numbers in v by index.
30
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> v = {3, 8, 1, 9, 4, 5};7 int sum = 0;8 // i goes from 0 to v.size() - 19 cout << sum << "\n";10 return 0;11}
With the STL
A fixed array's size is set when you write the program. vector<int> is the standard library's array: its elements are also in one contiguous block (on the heap), its size can be chosen while the program runs, and it knows how many it holds (v.size()). So v[i], like a[i], is one address calculation: O(1).
What it adds is v.at(i): it checks i < v.size() first and throws an out_of_range exception when it isn't, instead of quietly reading something else.
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> v = {10, 20, 30, 40, 50};7 cout << "size = " << v.size() << "\n";8 cout << v[3] << " " << v.at(3) << "\n";9 cout << "&v[3] - &v[0] = " << &v[3] - &v[0] << "\n"; // one after another too10 vector<int> zeros(6); // size chosen at run time: six 0s11 zeros[2] = 7;12 for (int x : zeros)13 cout << x << " ";14 cout << "\n";15 try {16 cout << v.at(5) << "\n"; // checks the index: throws when it is out of range17 } catch (...) {18 cout << "at(5) is out of range: v only has 0 to " << v.size() - 1 << "\n";19 }20 return 0;21}
size = 5 40 40 &v[3] - &v[0] = 3 0 0 7 0 0 0 at(5) is out of range: v only has 0 to 4
fixed array int a[5] | vector<int> v | |
|---|---|---|
| memory | one block (on the stack for a local) | one block, on the heap |
| size | set when you write the program | set at run time, and can change (next two lessons) |
| how many | you keep track | v.size() |
[i] | O(1), no check | O(1), no check |
| bounds check | none | v.at(i), throws out_of_range |
vector<int> zeros(6) with round brackets is 6 elements, all 0; vector<int> v = {10, 20} with braces is just those two elements.
In interviews: "Why is indexing an array O(1)": contiguous memory, address = start + i × element size, one calculation. A vector's elements are contiguous too, so v[i] is also O(1), and &v[0] can be used as a plain array pointer. The follow-up on [] vs at(): [] doesn't check (fast), at() checks and throws.
Round brackets and curly braces make different vectors. What does it print?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> v(4);7 v[1] = 5;8 vector<int> w = {4};9 cout << v.size() << " " << v[1] + v[2] << " " << w.size() << "\n";10 return 0;11}
vector<int> v(4) is 4 elements, all 0; after v[1] becomes 5, v[1] + v[2] = 5 + 0 = 5. vector<int> w = {4} uses curly braces: just one element, 4, so its size is 1.Summary
Arrays and vector: one contiguous block, indexing is O(1)
- address of a[i] = start + i × element size
- a[i] is *(a + i); indexes start at 0
- arrays and v[i] don't check bounds: loop with i < n
- a vector is contiguous too; v.at(i) checks and throws when out of range
- address of m[i][j] = start + (i × columns + j) × element size
1int a[5];2a[i] // element i, its address in one step3*(a + i) // the same thing4vector<int> v(n); // n zeros5for (int i = 0; i < n; i++) // not i <= n