unfried.
Streak:0 days XP:0

Formula sheet

C++

95 entries in 12 units. Free to use and share.

Jump to a unit (12 units)

Unit 1 First programs and the build

Shape of a C++ program

Also called hello world, main function, program skeleton.

A run starts at int main() { and carries out the statements inside the braces, top to bottom, once each.

#include <iostream>
using namespace std;
int main() {
    cout << "Hello, egg" << endl;
    return 0;
}

Careful: return 0; ends the run, so a statement after it never runs. Lines above main are not part of the run.

Taught in The shape of a program

Printing with cout

Also called output stream, string literal, endl.

Text in quotes prints exactly as typed; without quotes, C++ works the value out first.

cout << "2 + 3" << endl;   // 2 + 3
cout << 2 + 3 << endl;     // 5
cout << "Sum: " << 5;      // no line break
cout << endl;              // ends the line

Careful: << adds no spaces and a statement does not end the line. Only endl or "\n" starts a new line.

Taught in Printing text and numbers

Escape sequences and comments

WritePrints
\na line break, like endl
\ta tab, to the next tab stop
\"a double quote
//starts a comment to the end of the line
/* … */a comment over any number of lines

Careful: Inside quotes, // is ordinary text: cout << "//"; prints //.

Taught in Exact output: spaces, breaks and escapes

Building and running

Also called compile, g++ command, executable.

g++ checks and translates the whole file, the linker joins in the library, and the result is the executable hello, which ./hello runs.

g++ -std=c++17 -Wall hello.cpp -o hello
./hello

Careful: With any compile error nothing runs, not even the lines above it. After editing the source, compile again before running.

Taught in Source, compiler, program

Reading a g++ message

Also called compiler error, error message, syntax error.

File, line, column, then the message. The line and column are where g++ noticed the problem.

nosemi.cpp:4:17: error: expected ';' before 'return'

Careful: The mistake can be earlier than the line named, and one mistake can give several messages. Fix the first message, then compile again.

Taught in Reading a compiler error

#include and the std namespace

Also called header, using namespace std, std::cout.

LineWhat it does
#include <iostream>declares cout and endl
#include <string>declares string
using namespace std;lets you write cout for std::cout

Careful: Without the header: 'cout' was not declared in this scope. Without the using line: the same, with did you mean 'std::cout'?.

Taught in Names from the library: #include and std

Three kinds of error

Also called linker error, run-time error, compile error.

KindYou seeDid it run?
Compilea message with a line and columnno
Linkerundefined reference to `main', ld returned 1 exit statusno
Run timesome output, then the run stopspartly
Wrong answerno message, wrong outputyes

Careful: A program that builds with no errors can still be wrong, and a warning often marks a real bug.

Taught in Three kinds of error

Unit 2 Variables, types and arithmetic

Declaring and assigning a variable

Also called declaration, assignment, variable.

= works out its right side and copies the value into the variable on its left. The type is fixed at the declaration.

int a = 3;      // declare: type, name, value
int b = a;      // b gets a copy of 3
a = 7;          // only a changes; b is still 3

Careful: The left side must be a variable: 5 = x; does not compile. Storing text in an int is a compile error, not a change of type.

Taught in Declaring a variable

Initializing and const

Also called initialize, constant, uninitialized variable.

Give every variable a value when you declare it. const makes the compiler refuse any line that stores into the variable.

int total = 0;          // initialized
const double G = 9.81;  // can never change

Careful: A local variable declared with no value holds leftovers, and reading it can give anything. G = 10; is assignment of read-only variable 'G'.

Taught in Starting values and constants

Integer division and remainder

Also called % operator, modulo, quotient.

With two ints, / gives the whole part of the quotient and % the remainder.

ExpressionValue
7 / 23
17 % 52
5 / 90
-7 / 2−3
-7 % 2−1

Careful: The fraction is dropped toward zero, never rounded: -7 / 2 is −3, not −4 as in Python. With one double operand, / keeps the fraction.

Taught in Integer division and remainder

Mixing int and double, and static_cast

Also called type conversion, cast, static_cast.

The right side is worked out in its own operands' types before it is stored. One double operand makes the division exact.

double avg = 7 / 2;   // 3
double x = 7.0 / 2;   // 3.5
int n = 3.9;          // 3
static_cast<double>(7) / 2  // 3.5

Careful: The type of the variable on the left does not change the division. Storing a double in an int drops the fraction, with no warning.

Taught in Mixing int and double

Precedence and compound assignment

Also called order of operations, +=, pow.

*, / and % go before addition and subtraction; same-level operators go left to right. s += 5; means s = s + 5;.

ExpressionValue
2 + 3 * 414
(2 + 3) * 420
24 / 4 / 23
pow(2, 3)8

Careful: ^ is exclusive or, not a power: 2 ^ 3 is 1. Use pow from <cmath>, or multiply. x *= 2 + 1; multiplies by 3.

Taught in Operators and precedence

Range of int and overflow

Also called INT_MAX, long long, undefined behavior.

A signed result past the range is an overflow, which is undefined behavior: the standard promises nothing about what happens.

TypeBytes on g++Largest value
int42147483647
long long89223372036854775807

Careful: No error appears, and a run that looks right proves nothing. Choose long long or double before the value can get that big.

Taught in How big is an int? Overflow and undefined behavior

Doubles and what cout shows

Also called floating point, significant digits, comparing doubles.

Most decimals are stored approximately. cout shows 6 significant digits by default, so a printed value can hide a tiny error.

cout << 0.1 + 0.2;           // 0.3
cout << (0.1 + 0.2 == 0.3);  // 0
abs(t - 0.3) < 1e-9          // compare this way

Careful: Never use == on computed doubles; compare with a small tolerance. Count money in whole cents in an int.

Taught in Doubles are close, not exact

char and bool

Also called character code, boolalpha, true and false.

A char is stored as its code ('A' is 65, 'a' 97, '0' 48). A bool is true or false.

StatementPrints
char c = 'A'; cout << c;A
cout << c + 1;66
cout << (3 > 5);0
cout << boolalpha << true;true

Careful: Arithmetic on a char gives an int, which prints as a number until stored back in a char. A bool prints as 1 or 0 without boolalpha.

Taught in char and bool

Unit 3 Input, output and math

Reading with cin

Also called cin, extraction operator, input stream.

Each >> skips spaces and line breaks, then reads until the next whitespace or the first character that does not fit the type.

double a = 0, b = 0;
cin >> a >> b;    // "2.5 4" or "2.5⏎4"
string word;
cin >> word;      // "Ada Lovelace" gives "Ada"

Careful: >> never reads a space, so it can't read a full name or a phrase. Use getline for those.

Taught in Reading with cin

Reading a whole line

Also called getline, cin.ignore, leftover newline.

getline(cin, s) reads everything up to the next Enter, spaces included. cin.ignore(1000, '\n') throws away the rest of the current line.

int age = 0;
string name;
cin >> age;
cin.ignore(1000, '\n');
getline(cin, name);

Careful: Right after a >>, getline reads the empty rest of the line. Put cin.ignore(1000, '\n'); between them.

Taught in Whole lines: getline and the leftover newline

Decimal places with fixed and setprecision

Also called setprecision, fixed, iomanip, rounding output.

With fixed, setprecision(n) gives n places after the point; the setting stays until changed. Needs #include <iomanip>.

StatementPrints
cout << setprecision(2) << 3.14159;3.1
cout << fixed << setprecision(2) << 3.14159;3.14
cout << fixed << setprecision(2) << 2.5;2.50

Careful: Without fixed, n counts significant digits. Formatting changes the text only, never the stored value.

Taught in Fixed decimals with setprecision

Columns with setw

Also called setw, field width, left, right, setfill.

setw(n) pads the next item to at least n characters, on the left by default.

cout << setw(5) << 25;          // "   25"
cout << left << setw(5) << 25;  // "25   "
cout << setw(2) << setfill('0') << 5;  // "05"

Careful: setw lasts for one item only, so repeat it before each. left, right and setfill stay on until changed.

Taught in Columns with setw

Detecting bad input

Also called cin.fail, fail state, input validation.

A read that finds nothing it can use fails silently: the variable gets 0 and every later read is skipped.

int x = 0;
cin >> x;
if (cin.fail()) {
    cout << "Not a number" << endl;
    return 1;
}

Careful: Testing x == 0 can't tell a failed read from a typed 0. Input such as 12abc or 3.9 into an int does not fail: the read takes 12 or 3.

Taught in When input goes wrong

cmath functions

Also called sqrt, pow, abs, round, floor, ceil.

Include <cmath>. pow(a, b) is a to the power b; sin, cos and tan take radians.

CallPrints
sqrt(2.0)1.41421
pow(1.5, 2)2.25
round(2.5)3
floor(-2.5)-3
ceil(-2.5)-2

Careful: ^ is not a power in C++. M_PI is not standard: declare const double PI = 3.14159265358979;.

Taught in The cmath library

NaN and infinity

Also called nan, inf, not a number, division by zero.

Doubles have special values for "no real answer" (NaN) and infinity, and carry on with them.

ExpressionResult
sqrt(-1.0)-nan, run goes on
1.0 / 0inf, run goes on
1 / 0 with intsundefined; on g++ the run stops

Careful: Integer division by zero has no such value: it is undefined behavior, and on g++ the run stops with Floating point exception.

Taught in The cmath library

Read, compute, print

Also called unit converter, input processing output.

Declare inputs with types that fit, read, compute into a variable, set the format, then print with the unit. Typed 30, this prints 206.84 kPa.

double psi = 0;
cin >> psi;
double kpa = psi * 6.894757;
cout << fixed << setprecision(2);
cout << kpa << " kPa" << endl;

Careful: Two ints divide as ints even when the result goes into a double: write minutes / 60.0, not minutes / 60.

Taught in Read, compute, print

Unit 4 Decisions

if and else

Also called if statement, condition, branch.

Runs the first block when the condition is true, the second when it is false. Exactly one block runs.

if (t >= 100) {
    cout << "boiling" << endl;
} else {
    cout << "not yet" << endl;
}

Careful: At the boundary value > and >= differ: t > 100 is false for 100. C++ has no => or =<.

Taught in if and else

Relational operators

Also called comparison operators, equal, not equal.

OperatorMeaning
==equal
!=not equal
< and >less than, greater than
<= and >=at most, at least

Careful: One = assigns. if (x = 5) stores 5 and is always true; g++ warns suggest parentheses around assignment used as truth value.

Taught in = is not ==

Braces and the empty statement

Also called block, misleading indentation, semicolon after if.

Without braces an if controls exactly one statement; a ; right after if (…) is its whole body.

if (t > 100)
    cout << "hot" << endl;  // in the if
    cout << "boil" << endl; // always runs
if (t > 100); {             // empty body
    cout << "boiling" << endl; // always runs
}

Careful: Indentation means nothing to the compiler. Put braces on every body.

Taught in Braces decide, not indentation

else-if chain

Also called if else if, multiway branch, thresholds.

Tests from the top and runs only the first branch whose test is true; a final else runs if none is.

if (score >= 90) {
    cout << "A" << endl;
} else if (score >= 80) {
    cout << "B" << endl;
} else {
    cout << "F" << endl;
}

Careful: Test the highest threshold first. Separate ifs without else are each tested, so several can run.

Taught in else-if chains and their order

Logical operators

Also called and, or, not, range test.

WriteTrue when
a && bboth are true
a || bat least one is true
!aa is false
x > 0 && x < 10x is between 0 and 10

Careful: 0 < x < 10 and x == 1 || 2 compile but are always true. Write each side as a whole comparison: x == 1 || x == 2.

Taught in &&, ||, ! and two traps

Short-circuit guard

Also called short-circuit evaluation, divide by zero guard.

&& skips its right side when the left is false; || skips it when the left is true.

if (n != 0 && total / n > 2) {
    cout << "big" << endl;
}

Careful: The guard must be on the left. total / n > 2 && n != 0 divides first.

Taught in Short-circuit and comparing doubles

Comparing doubles with a tolerance

Also called floating point equality, epsilon, abs.

Two computed doubles count as equal when they differ by less than the tolerance.

if (abs(r - 330) < 0.001) {
    cout << "330 ohm" << endl;
}

Careful: == on computed doubles is unreliable: 0.1 + 0.2 == 0.3 is false. Without abs, every value below the target passes.

Taught in Short-circuit and comparing doubles

switch and break

Also called switch statement, case, fall-through, default.

Jumps to the matching case, or to default, and runs down until break;.

switch (unit) {
    case 'c':
        cout << "Celsius" << endl;
        break;
    default:
        cout << "unknown" << endl;
}

Careful: Without break the run falls through into the next case. Only integers and characters can be switched on: a string gives switch quantity not an integer.

Taught in switch and break

Dangling else

Also called nested if, else pairing.

Braces choose which if the else answers: here the outer one.

if (a > 0) {
    if (b > 0) {
        cout << "both" << endl;
    }
} else {
    cout << "a <= 0" << endl;
}

Careful: Without braces an else belongs to the nearest if without an else, whatever the indentation; g++ warns suggest explicit braces to avoid ambiguous 'else'.

Taught in Nested ifs and the dangling else

Unit 5 Loops

while loop

Also called loop, iteration, condition tested first.

The test runs before every iteration. True runs the block once more; false ends the loop.

int n = 0;
while (n < 3) {   // tested before each iteration
    cout << n;    // prints 012
    n++;          // the block must change n
}

Careful: The test is not watched while the block runs. If nothing in the block changes what it tests, the loop never ends.

Taught in while loops

Increment and decrement (x++ and ++x)

Also called postfix, prefix, increment operator.

With x = 5Value handed backx after
x++56
++x66
x--54
--x44

Careful: On a line of its own, i++; and ++i; do the same thing. x + 1; alone changes nothing.

Taught in ++, -- and compound updates

for loop and how many times it runs

Also called loop counter, off-by-one, for header.

HeaderValues of iRuns
i = 0; i < n; i++0 to n − 1n
i = 1; i <= n; i++1 to nn
i = 0; i <= n; i++0 to nn + 1
i = 1; i < n; i++1 to n − 1n − 1

Careful: A counter declared in the header does not exist after the loop. Declare it before the loop to use its final value.

Taught in for loops and off-by-one

Stray semicolon and infinite loops

Also called empty body, infinite loop, never ends.

A ; after the header is the loop's whole body. A test that can never become false makes an infinite loop.

for (i = 0; i < 3; i++);  // empty body
{ cout << i; }            // runs once: 3
while (n != 10) { n += 3; }  // skips 10

Careful: Stop a runaway program with Ctrl+C. When a counter jumps by more than 1, test with < or >, not !=.

Taught in Loops that misbehave

do-while loop

Also called input validation, test after.

The block runs first and the test comes after, so it always runs at least once. It repeats while the input is bad.

double r = 0;
do {
    cout << "Resistance?" << endl;
    cin >> r;
} while (r <= 0);

Careful: The ; after while (test) is required here. A while loop can run its block zero times; a do-while cannot.

Taught in do-while and checking input

Nested loop counts

Also called inner loop, loop inside a loop.

The inner loop runs completely on every outer iteration, so the counts multiply.

for (int r = 0; r < 3; r++) {
    for (int c = 0; c < 4; c++) {
        cout << "*";   // runs 3 × 4 = 12 times
    }
    cout << endl;      // once per row
}

Careful: When the inner loop's bounds use the outer counter, add the inner counts row by row instead of multiplying.

Taught in Nested loops

Accumulators, sentinels and the best so far

Also called running total, counter, sentinel, maximum.

ResultStart before the loopUpdate inside
Totalsum = 0sum += x;
Countcount = 0count++;
Productp = 1p *= x;
Largestthe first readingif (x > best) { best = x; }

Careful: A start inside the block restarts every iteration. A sentinel such as -999 ends the input and is never added. Check the count before dividing.

Taught in Counters, totals and the best so far

break and continue

Also called leave a loop, skip an iteration.

StatementWhat it does
break;ends the innermost loop or switch at once
continue;ends this iteration; the loop goes on

Careful: break in an inner loop leaves only the inner loop, and inside a switch it leaves only the switch.

Taught in break and continue

Unit 6 Functions

Function definition and call

Also called parameter, argument, return value.

The argument's value is copied into the parameter, by position. The call becomes the returned value, of the return type.

double toCelsius(double f) {
    return (f - 32) * 5 / 9;
}
double c = toCelsius(212); // 100

Careful: An int return type cuts a fraction off on the way out: int area(...) returns 7 for 7.5.

Taught in Defining and calling a function

Prototype (declare before use)

Also called function declaration, was not declared in this scope.

A function must be declared above its first call. A prototype is the header followed by ;.

int square(int x);   // prototype
int main() {
    cout << square(4);
}
int square(int x) {
    return x * x;
}

Careful: A prototype with no definition anywhere compiles, then fails at the linker: undefined reference to `square(int)'.

Taught in Declare before use: prototypes

return, cout and void

Also called void value not ignored, Wreturn-type.

return hands a value to the caller; cout only prints. A void call is a statement on its own.

FunctionCall used asGives back
int f(int x)int y = f(3);an int
void g(int x)g(3);nothing

Careful: An int function that can end without return only gets a warning; a call that ends that way is undefined behavior.

Taught in return, cout and void

Scope of a variable

Also called local variable, global, static local.

A local lives from its declaration to its block's }, fresh for each call. A global is visible to every function below it. A static local keeps its value between calls.

Careful: A local with the same name as a global hides it inside its block; changing it never changes the global.

Taught in Scope: where a variable lives

Pass by value and pass by reference

Also called int&, reference parameter, copy.

A value parameter is a copy of the argument. A reference parameter (int&) is another name for the caller's variable.

void addOne(int n)     { n++; } // copy
void addOneRef(int& n) { n++; } // x itself
int x = 5;
addOne(x);    // x is 5
addOneRef(x); // x is 6

Careful: A non-const reference needs a variable: addOneRef(5) and addOneRef(x + 1) do not compile.

Taught in Pass by reference

Default arguments and overloading

Also called default parameter, overloaded function.

A call may leave out parameters that have defaults. Among overloads, the call picks the version whose parameter types match its arguments.

double area(double w, double h = 1.0);
int twice(int x);       // twice(2)
double twice(double x); // twice(2.0)

Careful: Defaults go on the last parameters only, and functions that differ only in return type don't compile.

Taught in Default arguments and overloading

Recursion and the base case

Also called recursive function, factorial.

Each call has its own frame and waits for the call it made. The base case answers without calling again.

int fact(int n) {
    if (n <= 1) {
        return 1;     // base case
    }
    return n * fact(n - 1);
}

Careful: Without a reachable base case the calls pile up until the stack runs out, and with g++ on Linux the run crashes. int results past 2147483647 overflow, which is undefined.

Taught in A function that calls itself

Testing with assert

Also called cassert, edge case, boundary value.

A true condition does nothing; a false one stops the run with the file, line and condition. Test typical, boundary and edge values.

#include <cassert>
assert(toCelsius(212) == 100);
assert(abs(toCelsius(100) - 37.7778)
       < 0.001);

Careful: Never compare computed doubles with ==: use a tolerance. Passing tests never prove a function right.

Taught in Testing a function

Unit 7 Arrays

Declaring and indexing an array

Also called array, index, initializer list.

Indexes run from 0 to SIZE − 1. Elements an initializer list doesn't reach are 0; int z[4] = {}; is all zeros.

const int SIZE = 5;
int a[SIZE] = {1, 2, 3}; // 1 2 3 0 0
a[0]          // first element
a[SIZE - 1]   // last element

Careful: A local array with no initializer holds leftovers. The size must be a constant: int a[n]; with a typed n is not standard C++.

Taught in Declaring and indexing an array

Counting elements with sizeof

Also called sizeof(a) / sizeof(a[0]), array length.

Bytes in the whole array divided by bytes in one element gives the count.

int a[5];
sizeof(a)                // 20 bytes
sizeof(a) / sizeof(a[0]) // 5 elements

Careful: Inside a function the parameter is an address: sizeof gives 8, with the warning -Wsizeof-array-argument. Pass the count instead.

Taught in Declaring and indexing an array

Walking an array

Also called loop over an array, out of bounds, buffer overrun.

Start at 0 and test i < SIZE: every element once, never index SIZE.

for (int i = 0; i < SIZE; i++) {
    sum += a[i];
}

Careful: i <= SIZE reads a[SIZE], past the end. Nothing checks indexes, so this is undefined behavior, not an error message.

Taught in Walking an array, and running off the end

Copying and comparing arrays

Also called element-by-element copy, invalid array assignment, Warray-compare.

An array's name stands for the address of its first element. Copy and compare element by element.

LineWhat happens
b = a;compile error: invalid array assignment
a == bcompares addresses: false for two arrays
cout << a;prints an address
b[i] = a[i]; in a loopcopies every element

Taught in Arrays are not values

Arrays as parameters

Also called array parameter, const parameter, pass an array.

The function receives the address of the first element, so writes through a[i] change the caller's array. const forbids writes; pass the count as n.

double average(const double a[],
    int n) {
    double sum = 0;
    for (int i = 0; i < n; i++) {
        sum += a[i];
    }
    return sum / n;
}

Careful: No copy is made. A write to a const parameter is a compile error beginning assignment of read-only location.

Taught in Arrays and functions

Linear search

Also called find an element, not found, return -1.

Return the index at the first match; return -1 only after the loop has checked every element.

for (int i = 0; i < n; i++) {
    if (a[i] == t) {
        return i;
    }
}
return -1;

Careful: An else return -1; inside the loop gives up at the first mismatch. A missing value costs n comparisons.

Taught in Searching and the largest value

Largest or smallest (best so far)

Also called maximum, minimum, index of the largest.

at is the index of the largest so far; a[at] is its value. Use < for the smallest. With > a tie keeps the first.

int at = 0;
for (int i = 1; i < n; i++) {
    if (a[i] > a[at]) {
        at = i;
    }
}

Careful: Never start the best value at 0: with all-negative (or, for a minimum, all-positive) values it reports a number not in the array.

Taught in Searching and the largest value

Two-dimensional arrays

Also called 2D array, row and column, row-major order, grid.

Row first, then column, both from 0. Walk with nested loops, rows outside and columns inside. Rows are stored one after another (row-major order).

int g[2][3] = {{1, 2, 3},
               {4, 5, 6}};
g[1][0]   // row 1, column 0: 4

Careful: For double t[3][4], t[3][2] and t[0][4] are out of bounds: rows run 0 to 2, columns 0 to 3.

Taught in Two-dimensional arrays

Swapping two values

Also called swap, temporary variable.

Save one value before the first assignment overwrites it.

int t = a;
a = b;
b = t;      // or swap(a, b);

Careful: a = b; b = a; leaves both holding the old b.

Taught in Selection sort

Selection sort

Also called sorting, sort an array.

Each pass selects the smallest unsorted element and swaps it into place: one swap per pass. It makes (n − 1) + (n − 2) + … + 1 comparisons, 10 for 5 elements.

for (int i = 0; i < n - 1; i++) {
    int m = i;
    for (int j = i + 1; j < n; j++) {
        if (a[j] < a[m]) {
            m = j;
        }
    }
    swap(a[i], a[m]);
}

Careful: Start the inner loop at i + 1, after the sorted part. The work grows with the square of n.

Taught in Selection sort

Unit 8 Vectors

Declaring a vector

Also called vector constructor, v(5) and v{5}.

Round brackets give a count (and a value for every element); braces list the elements.

DeclarationHolds
vector<int> v;nothing (size 0)
vector<int> v(5);0 0 0 0 0
vector<int> v(3, 7);7 7 7
vector<int> v{5};5
vector<int> v = {3, 7};3 7

Taught in vector basics

Range-based for, by copy and by reference

Also called for each, loop reference, for (int& x : v).

The loop visits every element once, first to last.

for (int x : v)        // copy
for (int& x : v)       // element
for (const int& x : v) // read only

Careful: Changing a copy (int x) leaves the vector unchanged. Use int& to change elements.

Taught in Range-based for

Copy or share a vector

Also called value semantics, deep copy.

= copies every element of a vector, string or struct. A reference shares one vector.

vector<int> b = a;   // a copy
vector<int>& r = a;  // a second name

Careful: In Python, b = a names the same list; in C++ it makes a copy.

Taught in Copying a vector copies it

size() is unsigned (size_t)

Also called Wsign-compare, size minus one.

size() returns size_t, with no negative values: 0 − 1 wraps to 18446744073709551615. Write i < v.size() and v.size() > 0.

Careful: Never i <= v.size() - 1 or v.size() - 1 >= 0: both go wrong for an empty vector.

Taught in size() is unsigned

[] and at()

Also called out_of_range, bounds checking.

The message __n (which is 10) >= this->size() (which is 3) gives the index asked for, then the size.

AccessIndex past the end
v[i]undefined behavior, no check
v.at(i)throws out_of_range, the run stops

Careful: front(), back() and pop_back() don't check either: on an empty vector they are undefined.

Taught in [] or at()

Passing a vector to a function

Also called const reference, pass by reference.

A function that only reads takes a const reference.

ParameterCopies?Can change caller's?
vector<int> vyes, every elementno
vector<int>& vnoyes
const vector<int>& vnono

Taught in Vectors and functions

Binary search

Also called halving, sort.

Each middle checked halves the range: at most 10 checks for 1000 values. Sort first with sort(v.begin(), v.end()) from <algorithm>.

while (lo <= hi) {
    int mid = (lo + hi) / 2;
    if (v[mid] == t) {
        found = mid;
        break;
    } else if (v[mid] < t) {
        lo = mid + 1;
    } else {
        hi = mid - 1;
    }
}

Careful: On an unsorted vector it can miss a value that is there. lo = mid can loop forever.

Taught in Sorting and binary search

Removing elements

Also called erase, pop_back, clear, filter.

pop_back() removes the last element, clear() all, erase(v.begin() + i) element i; later elements slide down one.

vector<int> keep;
for (int x : v) {
    if (x >= 0) {
        keep.push_back(x);
    }
}

Careful: Erasing inside a loop that always does i++ skips the element after each erase. Filter into a new vector instead.

Taught in Removing and filtering

Unit 9 Strings and characters

Strings can change

Also called std::string, length, index, concatenation.

Indexes run from 0 to s.length() - 1. s[i] is a char you can read or assign; += adds a char or text to the end.

string s = "hello";
s[0] = 'J';      // Jello
s += " world";   // Jello world
s.length()       // 11

Careful: [] never adds characters: writing at index s.length() or beyond is undefined behavior. s + "x" alone leaves s unchanged.

Taught in string basics

substr and find

Also called substring, npos, string::npos.

The second number of substr is how many characters to take. find returns the first match's index, or string::npos.

string s = "hello";
s.substr(1, 3)   // "ell": start, count
s.substr(2)      // "llo": to the end
s.find("l")      // 2
s.find('z') == string::npos  // true

Careful: A Python slice s[1:4] stops before index 4; substr(1, 3) takes 3. "Not found" is npos, never -1; test for it before using the index.

Taught in substr and find

Joining text and numbers

Also called to_string, stoi, stod, conversion function, string literal.

+ joins text when at least one side is a string. Convert numbers with to_string, and text with stoi or stod.

ExpressionGives
to_string(42) + "!"the text 42!
stoi("17") + 1the int 18
stod("2.5") * 2the double 5
"abc" + "def"compile error
s + 5compile error

Careful: stoi("abc") stops the run with std::invalid_argument. "Total: " + 5 compiles but does not join: it skips 5 characters of the literal.

Taught in Joining text and numbers

char or string, and comparing text

Also called character literal, lexicographic order, string comparison.

'a' is one char, "a" is text. Strings compare character by character by code, so capitals come first and digits before letters.

ComparisonResult
string("apple") < "banana"true
string("Zebra") < "apple"true
string("10") < "9"true
string("egg") == "Egg"false

Careful: Compare s[0] with 'y', not "y". == compares text only for strings, not for two char arrays.

Taught in char or string, and comparing text

Character tests and toupper

Also called cctype, isdigit, isalpha, tolower.

isdigit, isalpha, isupper and isspace test one char and give nonzero for yes. toupper and tolower return a code.

for (char& ch : s) {
    ch = toupper(ch);
}
if (isdigit(c)) { ... }

Careful: cout << toupper('a') prints 65; store the result in a char or write char(toupper(c)). Without & the loop changes copies.

Taught in Walking a string with cctype

Character codes (ASCII)

Also called ASCII, character code, digit value.

ch - '0' is a digit character's value; ch - 'A' is a capital's place from 0; char('A' + 2) is C.

CharactersCodes
'0' to '9'48 to 57
'A' to 'Z'65 to 90
'a' to 'z'97 to 122

Careful: A char in arithmetic is an int: '7' + 1 prints 56, and total += ch adds codes, not digits.

Taught in Characters are numbers

C-strings and strcmp

Also called null terminator, strlen, cstring, char array.

A C-string ends with '\0', so text of length n needs an array of at least n + 1. strlen and strcmp come from <cstring>.

char name[6] = "hello";  // 5 + '\0'
strlen(name)    // 5
sizeof(name)    // 6
strcmp(a, b) == 0  // same text

Careful: a == b on two arrays compares addresses and is false even for equal text. string s = name; converts to a string.

Taught in C-strings

Unit 10 Pointers and references

Address-of and dereference

Also called pointer, &x, *p.

&x is the address of x. A pointer holds an address; *p is the variable it points at.

int x = 5;
int* p = &x; // points at x
*p = 7;      // x is now 7
p = &y;      // now at y

Careful: In a declaration the * belongs to each name: int* p, q; makes q an int. Write int *p, *q;.

Taught in Pointers

The two meanings of &

Also called ampersand, reference or address.

The position decides which one it is.

Where & standsExampleMeaning
After a type, in a declarationint& r = x;a reference to x
Before a name, in an expressioncout << &x;the address of x

Careful: A printed address changes from run to run: never depend on its digits.

Taught in Addresses

Null pointers

Also called nullptr, segmentation fault.

Initialize every pointer, to an address or nullptr, and test it before following it.

int* p = nullptr;
if (p != nullptr && *p > 0) {
    cout << *p << endl;
}

Careful: Dereferencing a null or uninitialized pointer is undefined behavior; it often, but not always, stops the run. A null test can't catch an uninitialized pointer.

Taught in nullptr and pointers to nowhere

Pointer parameters (output parameters)

The function gets a copy of the address, so writing *p changes the caller's variable.

void triple(int* p) {
    *p = *p * 3;
}
triple(&n);   // n is tripled

Careful: Assigning to p itself (p = nullptr;) changes only the function's copy.

Taught in Pointers as parameters

Pointer arithmetic and arrays

Also called array decay, *(a + i).

An array's name decays to a pointer to its first element. q + i moves i elements, i × sizeof bytes.

int a[3] = {10, 20, 30};
int* q = a;  // &a[0]
*(q + 1)     // 20, as q[1]
*q + 1       // 11

Careful: a + n points one past the end of an n-element array: compare with it, never read through it.

Taught in Pointers and arrays

new and delete

Also called heap, memory leak, delete[].

Heap memory stays until it is freed. Set the pointer to nullptr after freeing it.

AllocateFree with
int* p = new int(42);delete p;
double* a = new double[n];delete[] a;

Careful: Mixing delete and delete[] is undefined behavior, and a missing delete leaks. A vector frees its memory for you.

Taught in new and delete

References and pointers compared

Also called alias, rebinding.

A reference is a second name bound once; r = y copies y's value into what r names.

PropertyPointerReference
Can be nullyesno
Can be re-pointedyesno
Reach the value with*pr
Must be initializednoyes

Careful: Use a reference parameter when the argument must exist, a pointer when "nothing" is a valid argument.

Taught in References and pointers compared

Lifetimes and dangling pointers

Also called Wreturn-local-addr, use after delete.

A local's lifetime ends with its block. A pointer or reference to it, or to memory after delete, dangles: it still holds an address, but using it is undefined behavior.

Careful: Return a value or a vector by value, never the address of a local. Setting one pointer to nullptr leaves its copies dangling.

Taught in Lifetimes and dangling pointers

Unit 11 Structs and classes

Struct definition and copies

Also called struct, member, dot operator.

Members are filled in the order they are declared and reached with a dot. Assigning or passing a struct by value copies every member.

struct Point {
    int x;
    int y;
};
Point p = {3, 4};
Point q = p;  // a copy
q.x = 10;     // p.x is still 3

Careful: The definition ends with };. To change the caller's struct in a function, take it by reference: Point& p.

Taught in struct: grouping values

Class with private data

Also called class, object, encapsulation, invariant, public, private.

Members above public: are private: only member functions can use them, so they alone keep the invariant. Each object holds its own data.

class Account {
    double balance = 0;
public:
    void deposit(double amt) {
        if (amt > 0) {
            balance += amt;
        }
    }
};

Careful: A struct starts public and a class starts private. Naming a private member outside the class is a compile error.

Taught in public, private and invariants

Constructor with an initializer list

Also called constructor, initializer list, default constructor.

Named after the class, with no return type. Each entry in the list sets one member from a parameter as the object is made.

Rect(double w, double h)
    : width(w), height(h) {}
Rect r(3, 4.5);

Careful: Writing any constructor removes the empty one, so Rect r; needs a Rect() of its own. In the body, w = w; assigns the parameter to itself: use : w(w).

Taught in Constructors

const member function

Also called accessor, getter, discards qualifiers.

const after the parameter list promises not to change the object. Only const member functions can be called on a const object or through a const&.

double getBalance() const {
    return balance;
}

Careful: A function that changes a member can't be const (assignment of member … in read-only object).

Taught in const member functions

Header and source files

Also called include guard, scope resolution operator, ::, linker.

Build with every source file: g++ main.cpp account.cpp -o bank. #include pastes the header's text.

FileHolds
account.hthe class, with #ifndef/#define/#endif around it
account.cppthe bodies: void Account::deposit(double amt) { … }
main.cpp#include "account.h" and main

Careful: Without Account:: a body is a separate function that can't see the members. A source file left out of the build gives the linker's undefined reference.

Taught in Header and source files

When constructors and destructors run

Also called destructor, scope, lifetime, ~.

The destructor ~Noisy() runs by itself at the end of the object's lifetime.

ObjectMadeEnded
Local, Noisy a("a");at its lineat its block's }
From newat newat delete

Careful: Never call a destructor by hand. A new object that is never deleted never runs its destructor: a leak.

Taught in Constructors, destructors and scope

Looping over a vector of objects

Also called vector of objects, range for, const reference.

Read with const Rect&, change with Rect&.

LoopCopies?Can change?
for (Rect x : rs)yesonly the copy
for (Rect& x : rs)noyes
for (const Rect& x : rs)nono

Careful: With a plain Rect x, changes go to a copy that is thrown away each pass.

Taught in Vectors of objects

Unit 12 Files and streams

Opening a file for output

Also called ofstream, append mode, ios::app.

An ofstream is written with << like cout. A missing file is created either way.

OpeningOld contents
ofstream out("log.txt");erased
ofstream out("log.txt", ios::app);kept; writing goes after them

Careful: A plain opening erases the file even if nothing is written. To add to a log across runs, use ios::app.

Taught in Writing a file

Checking that a file opened

Also called ifstream, missing file, if (!in).

A failed open gives no message; it leaves the stream failed, and every read from it fails. Test straight after opening.

ifstream in("data.txt");
if (!in) {
    cout << "no file" << endl;
    return 1;
}

Careful: A relative name is looked up from the folder the program runs in, not the folder of the .cpp file. in.eof() is not a test for a failed open: it is false.

Taught in Opening a file for reading

Reading every value in a file

Also called eof loop, end of file, while (in >> x).

The read is the test, so the loop stops on the first read that fails. For whole lines, use while (getline(in, line)).

while (in >> x) {
    sum += x;
    count++;
}

Careful: while (!in.eof()) runs one extra pass, because eof() turns true only after a read tries to go past the end, and the last value is counted twice. Check count before dividing: an empty file gives 0.

Taught in Reading until the data runs out

>> or getline

Also called records, fields, leftover newline.

in >> name >> score reads one record such as Ada 92 per call.

CallReads
in >> sone field, up to a space or line break
getline(in, s)the whole line, spaces included
getline(ss, s, ',')up to the comma, which is dropped

Careful: After in >> n, a getline reads the rest of that line, often empty. Skip it with in.ignore(1000, '\n').

Taught in Lines and records

Splitting a line with a stringstream

Also called stringstream, delimiter, CSV, split.

A stringstream reads from a string; getline with a delimiter takes one field at a time, and stoi or stod turns a field into a number.

stringstream ss("Ada,92,88");
getline(ss, name, ',');  // "Ada"
getline(ss, f, ',');     // "92"
int a = stoi(f);

Careful: The delimiter is a char (',', not ","). stoi of an empty field or n/a stops the run with std::invalid_argument; leading spaces are fine.

Taught in Splitting a line

Formatting a report file

Also called setw, setprecision, fixed, table to a file.

The manipulators work on any output stream. fixed and setprecision stay set on their stream; setw sets the width of the next item only.

out << fixed << setprecision(1);
out << setw(4) << "T1";
out << setw(7) << 21.5 << endl;

Careful: Settings sent to cout do not reach out: each stream has its own. Write setw before every value in a column.

Taught in A formatted report to a file

Reading a data file into a vector of structs

Also called file report, read and split.

Open and check, read and split, store, compute, write. Pass the vector to functions as const vector<Reading>&, so it is not copied.

while (getline(in, line)) {
    stringstream ss(line);
    Reading r = {};
    string v;
    getline(ss, r.sensor, ',');
    getline(ss, v);
    r.value = stod(v);
    rs.push_back(r);
}

Careful: A line with a missing field makes stod stop the run; if (!getline(ss, v)) { continue; } skips such a line.

Taught in Putting it together