Appendix A — Appendix A: C++ Refresher

Appendix A: C++ Refresher

A one-page review of C++ idioms used throughout the book. If a chapter assumes something you do not remember, this is the first place to look.

A.1 Fundamental types

int i = 5;
long long bigInt = 9'000'000'000LL;
double d = 3.14;
char c = 'a';
bool b = true;
std::string s = "hello";

int overflow at ~±2 billion. For larger, long long. For floating-point, double (not float unless you really need the memory savings).

A.2 Strings

string s = "hello";
s.size();              // 5
s.length();            // same
s.substr(1, 3);        // "ell" — start 1, length 3
s.find("ll");          // 2
s + " world";          // concatenation
s[0];                  // 'h'
to_string(42);         // "42"
stoi("42");            // 42

A.3 Range-based for

for (int x : v)          // copy each
for (auto& x : v)        // reference, can modify
for (const auto& x : v)  // const reference, no copy, no modify
for (const auto& [k, v] : m)   // structured binding for pairs (C++17)

A.4 STL algorithms quick reference

#include <algorithm>

sort(v.begin(), v.end());
reverse(v.begin(), v.end());
swap(a, b);
auto it = find(v.begin(), v.end(), 42);
int count = count_if(v.begin(), v.end(), [](int x) { return x > 0; });
bool any = any_of(v.begin(), v.end(), [](int x) { return x < 0; });
bool all = all_of(v.begin(), v.end(), [](int x) { return x > 0; });
auto it2 = lower_bound(v.begin(), v.end(), 42);  // first not less than
auto it3 = upper_bound(v.begin(), v.end(), 42);  // first greater
int mn = *min_element(v.begin(), v.end());
int mx = *max_element(v.begin(), v.end());
int sum = accumulate(v.begin(), v.end(), 0);

A.5 Lambdas

auto add = [](int a, int b) { return a + b; };
add(3, 4);  // 7

// Capture by value
int factor = 10;
auto mult = [factor](int x) { return x * factor; };

// Capture by reference
int sum = 0;
auto addToSum = [&sum](int x) { sum += x; };

Common with STL:

sort(v.begin(), v.end(), [](int a, int b) { return a > b; });   // descending

A.6 I/O

#include <iostream>
using namespace std;

cin >> n;                  // read one int
cin >> s;                  // read one whitespace-delimited word
getline(cin, line);        // read one full line
cout << "hello" << endl;   // print with newline
cout << "x=" << x << ", y=" << y << "\n";   // chained
#include <sstream>

stringstream ss(s);
string word;
while (ss >> word) { /* tokenize on whitespace */ }

A.7 Pointer / reference cheat sheet

int x = 5;
int* p = &x;       // p points to x
int& r = x;        // r is another name for x

*p = 10;           // x is now 10
r = 20;            // x is now 20

p = nullptr;       // pointer to nothing

int arr[5];
int* q = arr;      // arrays decay to pointers
q[2] = 99;         // same as arr[2] = 99

new int(42);       // heap allocation; returns int*
new int[5];        // heap array
delete p;
delete[] arr;      // for arrays

A.8 Class skeleton (Rule of Three)

class Owns {
 public:
  Owns(int n);                          // constructor
  Owns(const Owns& other);              // copy constructor
  Owns& operator=(const Owns& other);   // copy assignment
  ~Owns();                              // destructor

 private:
  int* data_;
  int size_;
};

A.9 Templates quick form

template <typename T>
T maxOf(T a, T b) { return a > b ? a : b; }

template <typename T>
class Box {
 public:
  Box(T v) : v_(v) {}
  T get() const { return v_; }
 private:
  T v_;
};

Template implementations must be visible at the use site — usually in the header.

A.10 Common headers

Header What’s in it
<iostream> cin, cout, cerr, endl
<vector> vector
<string> string
<map>, <set> tree-backed associative containers
<unordered_map>, <unordered_set> hash-backed
<queue> queue, priority_queue
<stack> stack
<algorithm> sort, find, swap, etc.
<utility> pair, make_pair
<memory> unique_ptr, shared_ptr, make_unique
<numeric> accumulate, iota
<sstream> stringstream
<regex> regex
<cassert> assert
<climits> INT_MAX, INT_MIN
<cmath> sqrt, pow, abs

A.11 Compile commands

# Basic
g++ -Wall -Wextra -std=c++17 main.cpp -o main

# With debugging info
g++ -Wall -Wextra -std=c++17 -g main.cpp -o main

# With AddressSanitizer
g++ -Wall -Wextra -std=c++17 -g -fsanitize=address main.cpp -o main

# Multiple files
g++ -Wall -Wextra -std=c++17 main.cpp Box.cpp BST.cpp -o app