This collection provides 75 intermediate C++ programming exercises for developers who already know the basics (variables, loops, functions, and arrays) and want to move on to the features that make C++ powerful.
Each exercise includes a clear practice problem, the expected output, a helpful hint, a complete C++ solution, and a detailed explanation. Every solution compiles with a C++17 compiler, and every expected output shown here is the real output of the solution program.
Also, See: C++ Exercises with 11 topic-wise sets and 375+ practice questions. New to C++? Start with Basic C++ Exercises for Beginners.
What You’ll Practice
The exercises and coding challenges cover the following intermediate C++ topics:
- Loops, Arrays, Pointers & References (Exercises 1–8): Array algorithms, 2D matrices, pointer arithmetic, reference parameters, and function pointers.
- Dynamic Memory Allocation (Exercises 9–13):
new/delete, growing heap arrays, jagged 2D arrays, and a hand-built linked list. - Smart Pointers & RAII (Exercises 14–19):
std::unique_ptr,std::shared_ptr,std::weak_ptr, custom deleters, and scope guards. - Object-Oriented Programming (Exercises 20–29): Encapsulation, constructors, static members, inheritance, polymorphism, virtual destructors, friends, composition, and virtual inheritance.
- Operator Overloading (Exercises 30–35): Arithmetic, comparison, stream, subscript, increment, and function-call operators.
- Move Semantics & the Rule of Five (Exercises 36–40): rvalue references, move constructors, the Rule of Five,
emplace_back, and the copy-and-swap idiom. - STL Containers & Iterators (Exercises 41–48):
vector,map,unordered_set,stack,queue,priority_queue, anddeque. - STL Algorithms & Lambda Expressions (Exercises 49–56): Sorting with lambdas,
count_if,transform,accumulate, captures, erase-remove,std::function, binary search, and permutations. - Function & Class Templates (Exercises 57–62): Function templates, non-type parameters, class templates, specialization, variadic templates, and type traits.
- Exception Handling (Exercises 63–67): Throwing and catching, custom exceptions, catch order, stack unwinding, and exception-safety guarantees.
- File I/O & Namespaces (Exercises 68–71): Text, CSV, and binary files, plus nested, aliased, and anonymous namespaces.
- Modern C++ (C++17) Features (Exercises 72–75): Structured bindings,
std::optional,std::variant/std::visit,enum class, andconstexpr.
+ Table Of Contents
Table of contents
- Exercise 1: Second Largest Element in an Array
- Exercise 2: Rotate an Array Left by K Positions
- Exercise 3: Matrix Multiplication
- Exercise 4: Spiral Order Traversal of a Matrix
- Exercise 5: Array Traversal Using Pointer Arithmetic
- Exercise 6: Reverse an Array In-Place Using Two Pointers
- Exercise 7: Return Multiple Values Using References
- Exercise 8: Array of Function Pointers
- Exercise 9: Dynamic Array with new[] and delete[]
- Exercise 10: Grow a Dynamic Array
- Exercise 11: Jagged 2D Array: Pascal’s Triangle
- Exercise 12: Dynamic Stack Class That Grows Automatically
- Exercise 13: Singly Linked List with Manual Memory Management
- Exercise 14: unique_ptr Basics and Ownership Transfer
- Exercise 15: Vector of unique_ptr
- Exercise 16: shared_ptr and Reference Counting
- Exercise 17: Break a Cyclic Reference with weak_ptr
- Exercise 18: unique_ptr with a Custom Deleter
- Exercise 19: RAII Scope Guard
- Exercise 20: Bank Account Class with Encapsulation
- Exercise 21: Constructor Overloading and Delegating Constructors
- Exercise 22: Static Members: Count Live Objects
- Exercise 23: Inheritance: Employee and Manager
- Exercise 24: Abstract Class and Runtime Polymorphism
- Exercise 25: Why Destructors Must Be Virtual
- Exercise 26: Friend Function: Distance Between Two Points
- Exercise 27: Composition: Car Has an Engine
- Exercise 28: Diamond Problem and Virtual Inheritance
- Exercise 29: const Member Functions and mutable
- Exercise 30: Complex Number Class with Arithmetic Operators
- Exercise 31: Fraction Class with Automatic Reduction
- Exercise 32: Vector2D: Unary, Compound, and Scalar Operators
- Exercise 33: Bounds-Checked Array with operator[]
- Exercise 34: Prefix and Postfix Increment Operators
- Exercise 35: Function Call Operator: Polynomial Functor
- Exercise 36: lvalue vs rvalue References
- Exercise 37: Move Constructor vs Copy Constructor
- Exercise 38: Rule of Five: A Complete Resource-Owning Class
- Exercise 39: Copies vs Moves When Filling a Vector
- Exercise 40: Copy-and-Swap Idiom
- Exercise 41: Erase Elements from a Vector While Iterating
- Exercise 42: Word Frequency Counter with std::map
- Exercise 43: Remove Duplicates While Preserving Order
- Exercise 44: Balanced Brackets Using std::stack
- Exercise 45: Generate Binary Numbers Using std::queue
- Exercise 46: Task Scheduler with std::priority_queue
- Exercise 47: Group Anagrams Using a Map of Vectors
- Exercise 48: Sliding Window Maximum with std::deque
- Exercise 49: Sort Structs by Multiple Criteria with a Lambda
- Exercise 50: count_if, find_if, all_of, any_of
- Exercise 51: transform and accumulate
- Exercise 52: Lambda Captures: By Value, By Reference, and mutable
- Exercise 53: Erase-Remove Idiom and partition
- Exercise 54: Calculator Using std::function and a Map of Lambdas
- Exercise 55: Binary Search with lower_bound and upper_bound
- Exercise 56: Permutations with next_permutation
- Exercise 57: Generic findMax Function Template
- Exercise 58: Template with a Non-Type Parameter
- Exercise 59: Generic Stack Class Template
- Exercise 60: Class Template Specialization
- Exercise 61: Variadic Templates and Fold Expressions
- Exercise 62: Constraining Templates with Type Traits and if constexpr
- Exercise 63: Throw and Catch a runtime_error
- Exercise 64: Custom Exception Class
- Exercise 65: Multiple catch Blocks and Catch Order
- Exercise 66: Stack Unwinding and Rethrowing
- Exercise 67: Strong Exception Guarantee: Transaction Rollback
- Exercise 68: Write, Append, and Read a Text File
- Exercise 69: Parse a CSV File into Structs
- Exercise 70: Binary File I/O with Structs
- Exercise 71: Namespaces: Nested, Aliases, and Anonymous
- Exercise 72: Structured Bindings with Pairs, Tuples, and Maps
- Exercise 73: std::optional for Values That May Be Missing
- Exercise 74: Type-Safe Unions with std::variant and std::visit
- Exercise 75: enum class, constexpr, and switch
Exercise 1: Second Largest Element in an Array
Practice Problem: Write a C++ program to find the second largest distinct element in an integer array using a single loop. Do not sort the array.
Given:
int arr[] = {12, 35, 1, 10, 34, 35, 1};Code language: Python (python)
Expected Output:
Largest element: 35
Second largest element: 34
+ Hint
- Keep two variables,
largestandsecond, and initialize both toINT_MINfrom<climits>. - When an element is bigger than
largest, the oldlargestbecomessecond. When it is betweensecondandlargest(and not equal tolargest), update onlysecond.
+ Show Solution
#include <iostream>
#include <climits>
int main() {
int arr[] = {12, 35, 1, 10, 34, 35, 1};
int n = sizeof(arr) / sizeof(arr[0]);
int largest = INT_MIN, second = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] > largest) {
second = largest; // old largest moves down
largest = arr[i];
} else if (arr[i] > second && arr[i] != largest) {
second = arr[i];
}
}
std::cout << "Largest element: " << largest << std::endl;
if (second == INT_MIN)
std::cout << "No second largest element" << std::endl;
else
std::cout << "Second largest element: " << second << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The array is scanned only once, so the time complexity is O(n), which is better than sorting (O(n log n)).
- Whenever a new maximum is found, the previous maximum is pushed down into
secondbeforelargestis replaced. - The condition
arr[i] != largestmakes sure duplicate maximum values (35 appears twice) are not counted as the second largest.
Exercise 2: Rotate an Array Left by K Positions
Practice Problem: Write a C++ program that rotates an array to the left by k positions in place using the reversal algorithm (no extra array).
Given:
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int k = 3;Code language: Python (python)
Expected Output:
Original array: 1 2 3 4 5 6 7
After rotating left by 3: 4 5 6 7 1 2 3
+ Hint
- A left rotation by k can be done in three reversals: reverse the first k elements, reverse the remaining n-k elements, then reverse the whole array.
- Use
k = k % nso that values of k larger than the array size still work.
+ Show Solution
#include <iostream>
void reverse(int arr[], int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void rotateLeft(int arr[], int n, int k) {
k = k % n;
reverse(arr, 0, k - 1); // reverse first k elements
reverse(arr, k, n - 1); // reverse the rest
reverse(arr, 0, n - 1); // reverse whole array
}
void print(const int arr[], int n) {
for (int i = 0; i < n; i++) std::cout << arr[i] << " ";
std::cout << std::endl;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
std::cout << "Original array: ";
print(arr, n);
rotateLeft(arr, n, k);
std::cout << "After rotating left by " << k << ": ";
print(arr, n);
return 0;
}Code language: C++ (cpp)
Explanation:
- The helper
reverse()swaps elements from both ends moving toward the middle. - For {1,2,3,4,5,6,7} with k = 3: reversing the first part gives {3,2,1,…}, reversing the second part gives {…,7,6,5,4}, and reversing everything produces {4,5,6,7,1,2,3}.
- This approach runs in O(n) time and uses O(1) extra space.
Exercise 3: Matrix Multiplication
Practice Problem: Write a C++ program to multiply two matrices using 2D arrays. Matrix A is 2×3 and matrix B is 3×2, so the result is a 2×2 matrix.
Given:
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[3][2] = {{7, 8}, {9, 10}, {11, 12}};Code language: Python (python)
Expected Output:
Result of A x B:
58 64
139 154
+ Hint
- The element
C[i][j]is the sum ofA[i][k] * B[k][j]for every k from 0 to the number of columns of A. - You need three nested loops: rows of A, columns of B, and the shared dimension.
+ Show Solution
#include <iostream>
int main() {
const int R1 = 2, C1 = 3, C2 = 2;
int A[R1][C1] = {{1, 2, 3},
{4, 5, 6}};
int B[C1][C2] = {{7, 8},
{9, 10},
{11, 12}};
int C[R1][C2] = {};
for (int i = 0; i < R1; i++) {
for (int j = 0; j < C2; j++) {
for (int k = 0; k < C1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
std::cout << "Result of A x B:" << std::endl;
for (int i = 0; i < R1; i++) {
for (int j = 0; j < C2; j++) {
std::cout << C[i][j] << "\t";
}
std::cout << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Multiplication is only possible when the number of columns in A equals the number of rows in B (3 here).
- The result matrix
Cis initialized with empty braces{}so every element starts at zero before the sums are added. - For example,
C[0][0] = 1*7 + 2*9 + 3*11 = 58.
Exercise 4: Spiral Order Traversal of a Matrix
Practice Problem: Write a C++ program to print the elements of a 4×4 matrix in spiral order (clockwise, starting from the top-left corner).
Given:
int m[4][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};Code language: Python (python)
Expected Output:
Spiral order: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
+ Hint
- Maintain four boundaries:
top,bottom,left, andright. - Traverse the top row left to right, the right column top to bottom, the bottom row right to left, and the left column bottom to top. Shrink the matching boundary after each pass.
+ Show Solution
#include <iostream>
int main() {
const int N = 4;
int m[N][N] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
int top = 0, bottom = N - 1, left = 0, right = N - 1;
std::cout << "Spiral order: ";
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) std::cout << m[top][j] << " ";
top++;
for (int i = top; i <= bottom; i++) std::cout << m[i][right] << " ";
right--;
if (top <= bottom) {
for (int j = right; j >= left; j--) std::cout << m[bottom][j] << " ";
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) std::cout << m[i][left] << " ";
left++;
}
}
std::cout << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Each
forloop prints one side of the current outer layer, then moves the corresponding boundary inward. - The
if (top <= bottom)andif (left <= right)checks prevent printing a row or column twice when the matrix is not square or has an odd size. - The loop stops when the boundaries cross, which means every element has been printed exactly once.
Exercise 5: Array Traversal Using Pointer Arithmetic
Practice Problem: Write a C++ program that calculates the sum and finds the maximum of an array using only a pointer and pointer arithmetic (do not use the [] index operator).
Given:
int arr[] = {4, 9, 2, 15, 7, 11};Code language: Python (python)
Expected Output:
Elements: 4 9 2 15 7 11
Sum: 48
Max: 15
Third element using *(arr + 2): 2
+ Hint
- An array name decays to a pointer to its first element, so
int* p = arr;points toarr[0]. *(p + i)is the same asarr[i]. You can also move the pointer itself withp++until it reachesarr + n.
+ Show Solution
#include <iostream>
int main() {
int arr[] = {4, 9, 2, 15, 7, 11};
int n = sizeof(arr) / sizeof(arr[0]);
int* p = arr; // points to arr[0]
int* end = arr + n; // one past the last element
int sum = 0;
int maxVal = *p;
while (p != end) {
sum += *p;
if (*p > maxVal) maxVal = *p;
p++; // move to the next element
}
std::cout << "Elements: ";
for (int* q = arr; q < arr + n; q++) std::cout << *q << " ";
std::cout << std::endl;
std::cout << "Sum: " << sum << std::endl;
std::cout << "Max: " << maxVal << std::endl;
std::cout << "Third element using *(arr + 2): " << *(arr + 2) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
arr + nis a pointer to one position past the last element. It is safe to compare against but must never be dereferenced.p++advances the pointer bysizeof(int)bytes, so it lands exactly on the next integer.*(arr + 2)shows that indexing is just pointer arithmetic: the compiler turnsarr[2]into*(arr + 2).
Exercise 6: Reverse an Array In-Place Using Two Pointers
Practice Problem: Write a function reverseArray(int* begin, int* end) that reverses an array in place using two pointers that move toward each other.
Given:
int arr[] = {10, 20, 30, 40, 50, 60};Code language: Python (python)
Expected Output:
Before: 10 20 30 40 50 60
After: 60 50 40 30 20 10
+ Hint
- Start one pointer at the first element and one at the last element (
end - 1). - Swap the values the pointers point to, then move the left pointer forward and the right pointer backward until they meet.
+ Show Solution
#include <iostream>
void reverseArray(int* begin, int* end) {
int* left = begin;
int* right = end - 1;
while (left < right) {
int temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
int main() {
int arr[] = {10, 20, 30, 40, 50, 60};
int n = sizeof(arr) / sizeof(arr[0]);
std::cout << "Before: ";
for (int i = 0; i < n; i++) std::cout << arr[i] << " ";
std::cout << std::endl;
reverseArray(arr, arr + n);
std::cout << "After: ";
for (int i = 0; i < n; i++) std::cout << arr[i] << " ";
std::cout << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The function receives a half-open range
[begin, end), the same convention the STL uses for iterators. - Pointers can be compared with
<when they point into the same array, soleft < rightstops the loop at the middle. - Because the function works through pointers, the original array in
main()is modified directly.
Exercise 7: Return Multiple Values Using References
Practice Problem: Write a function analyze() that receives a std::vector<int> by const reference and returns the minimum, maximum, and average through reference parameters.
Given:
std::vector<int> scores = {78, 92, 65, 88, 99, 71};Code language: Python (python)
Expected Output:
Lowest: 65
Highest: 99
Average: 82.1667
+ Hint
- Pass the vector as
const std::vector<int>&to avoid copying it and to prevent modification. - Declare the output parameters as
int& minVal, int& maxVal, double& avgso the function can write into the caller’s variables.
+ Show Solution
#include <iostream>
#include <vector>
void analyze(const std::vector<int>& data, int& minVal, int& maxVal, double& avg) {
minVal = data[0];
maxVal = data[0];
long long sum = 0;
for (int value : data) {
if (value < minVal) minVal = value;
if (value > maxVal) maxVal = value;
sum += value;
}
avg = static_cast<double>(sum) / data.size();
}
int main() {
std::vector<int> scores = {78, 92, 65, 88, 99, 71};
int lowest, highest;
double average;
analyze(scores, lowest, highest, average);
std::cout << "Lowest: " << lowest << std::endl;
std::cout << "Highest: " << highest << std::endl;
std::cout << "Average: " << average << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- A reference is an alias for an existing variable. Assigning to
minValinside the function actually assigns tolowestinmain(). - The
constreference for the input vector gives the speed of pass-by-reference with the safety of pass-by-value. static_cast<double>converts the sum before division so the average keeps its decimal part.
Exercise 8: Array of Function Pointers
Practice Problem: Write a C++ calculator that stores four arithmetic functions (add, subtract, multiply, divide) in an array of function pointers and calls each one in a loop.
Given:
double x = 20, y = 8;Code language: Python (python)
Expected Output:
Add: 20 + 8 = 28
Subtract: 20 - 8 = 12
Multiply: 20 * 8 = 160
Divide: 20 / 8 = 2.5
+ Hint
- The type of a pointer to a function taking two
doubles and returningdoubleisdouble (*)(double, double). - A
usingalias such asusing Operation = double (*)(double, double);makes the array declaration easier to read.
+ Show Solution
#include <iostream>
double add(double a, double b) { return a + b; }
double subtract(double a, double b) { return a - b; }
double multiply(double a, double b) { return a * b; }
double divide(double a, double b) { return a / b; }
using Operation = double (*)(double, double);
int main() {
Operation ops[] = {add, subtract, multiply, divide};
const char* names[] = {"Add", "Subtract", "Multiply", "Divide"};
const char symbols[] = {'+', '-', '*', '/'};
double x = 20, y = 8;
for (int i = 0; i < 4; i++) {
double result = ops[i](x, y); // call through the pointer
std::cout << names[i] << ": " << x << " " << symbols[i] << " "
<< y << " = " << result << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- A function name used without parentheses decays to a pointer to that function, so
addcan be stored directly in the array. ops[i](x, y)calls the function stored at index i. This pattern is a simple form of a dispatch table.- Function pointers let you choose behavior at runtime without long
if-elseorswitchchains.
Exercise 9: Dynamic Array with new[] and delete[]
Practice Problem: Write a C++ program that allocates an integer array of size n on the heap using new[], fills it with the squares of 1 to n, prints it, and releases the memory with delete[].
Given:
int n = 8;Code language: Python (python)
Expected Output:
Squares: 1 4 9 16 25 36 49 64
Memory released. arr is nullptr
+ Hint
int* arr = new int[n];allocates n integers on the heap and returns a pointer to the first one.- Memory allocated with
new[]must be released withdelete[](not plaindelete). Set the pointer tonullptrafterward to avoid a dangling pointer.
+ Show Solution
#include <iostream>
int main() {
int n = 8;
int* arr = new int[n]; // allocate on the heap
for (int i = 0; i < n; i++) {
arr[i] = (i + 1) * (i + 1);
}
std::cout << "Squares: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
delete[] arr; // release the memory
arr = nullptr; // avoid a dangling pointer
std::cout << "Memory released. arr is "
<< (arr == nullptr ? "nullptr" : "not null") << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Unlike a normal array, the size of a heap array can be decided at runtime, which is why
ndoes not need to be a constant. - The heap memory stays allocated until
delete[]is called. Forgetting it causes a memory leak. - After
delete[], the pointer still holds the old address. Assigningnullptrmakes any later accidental use easy to detect.
Exercise 10: Grow a Dynamic Array
Practice Problem: Write a function int* resize(int* oldArr, int oldSize, int newSize) that creates a bigger heap array, copies the old elements, fills new slots with 0, frees the old array, and returns the new pointer.
Given:
int* data = new int[4]{5, 10, 15, 20};
int newSize = 7;Code language: Python (python)
Expected Output:
Before resize: 5 10 15 20 (size 4)
After resize: 5 10 15 20 25 30 0 (size 7)
+ Hint
- Allocate the new block first, then copy with a loop (or
std::copy), and only thendelete[]the old block. - The caller must replace its pointer with the returned one, because the old address is no longer valid.
+ Show Solution
#include <iostream>
int* resize(int* oldArr, int oldSize, int newSize) {
int* newArr = new int[newSize];
for (int i = 0; i < newSize; i++) {
newArr[i] = (i < oldSize) ? oldArr[i] : 0;
}
delete[] oldArr; // free the old block
return newArr;
}
void print(const int* arr, int size) {
for (int i = 0; i < size; i++) std::cout << arr[i] << " ";
std::cout << "(size " << size << ")" << std::endl;
}
int main() {
int size = 4;
int* data = new int[size]{5, 10, 15, 20};
std::cout << "Before resize: ";
print(data, size);
int newSize = 7;
data = resize(data, size, newSize);
size = newSize;
data[4] = 25; // use the new slots
data[5] = 30;
std::cout << "After resize: ";
print(data, size);
delete[] data;
return 0;
}Code language: C++ (cpp)
Explanation:
- Heap arrays cannot be grown in place, so resizing always means allocate → copy → free. This is exactly what
std::vectordoes internally when it runs out of capacity. new int[size]{5, 10, 15, 20}uses brace initialization to set the first values directly.- Slots beyond the old size are set to 0 so the program never reads uninitialized memory.
Exercise 11: Jagged 2D Array: Pascal’s Triangle
Practice Problem: Write a C++ program that builds the first 6 rows of Pascal’s triangle in a jagged 2D array allocated with int**, where row i has exactly i + 1 elements. Free all memory at the end.
Given:
int rows = 6;Code language: Python (python)
Expected Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
+ Hint
- First allocate an array of row pointers:
int** tri = new int*[rows];. Then allocate each row separately withnew int[i + 1]. - The first and last element of each row are 1. Every inner element is the sum of the two elements above it.
- Free each row with
delete[]before freeing the array of pointers.
+ Show Solution
#include <iostream>
int main() {
int rows = 6;
int** tri = new int*[rows];
for (int i = 0; i < rows; i++) {
tri[i] = new int[i + 1]; // row i has i+1 elements
tri[i][0] = tri[i][i] = 1;
for (int j = 1; j < i; j++) {
tri[i][j] = tri[i - 1][j - 1] + tri[i - 1][j];
}
}
for (int i = 0; i < rows; i++) {
for (int s = 0; s < rows - i - 1; s++) std::cout << " ";
for (int j = 0; j <= i; j++) std::cout << tri[i][j] << " ";
std::cout << std::endl;
}
for (int i = 0; i < rows; i++) {
delete[] tri[i]; // free each row
}
delete[] tri; // free the row pointers
return 0;
}Code language: C++ (cpp)
Explanation:
- A jagged array saves memory because each row is allocated with only the space it needs.
tri[i - 1][j - 1] + tri[i - 1][j]uses the previous row, which is already fully computed.- Deallocation happens in the reverse order of allocation: rows first, then the pointer array. Reversing that order would leak every row.
Exercise 12: Dynamic Stack Class That Grows Automatically
Practice Problem: Create a class IntStack that stores integers in a heap array. It should start with capacity 2, double its capacity when full, and free its memory in the destructor. Implement push(), pop(), top(), and empty().
Expected Output:
push 10
push 20
push 30
[capacity grown to 4]
push 40
push 50
[capacity grown to 8]
Popping: 50 40 30 20 10
+ Hint
- Keep three members:
int* data,int size, andint capacity. - In
push(), ifsize == capacity, allocate a new array ofcapacity * 2, copy the elements, and delete the old array. - Delete the copy constructor and copy assignment so two stacks never share (and double-free) the same array.
+ Show Solution
#include <iostream>
class IntStack {
int* data;
int size;
int capacity;
void grow() {
int newCap = capacity * 2;
int* bigger = new int[newCap];
for (int i = 0; i < size; i++) bigger[i] = data[i];
delete[] data;
data = bigger;
capacity = newCap;
std::cout << " [capacity grown to " << capacity << "]" << std::endl;
}
public:
IntStack() : data(new int[2]), size(0), capacity(2) {}
~IntStack() { delete[] data; }
IntStack(const IntStack&) = delete;
IntStack& operator=(const IntStack&) = delete;
void push(int value) {
if (size == capacity) grow();
data[size++] = value;
}
void pop() { if (size > 0) size--; }
int top() const { return data[size - 1]; }
bool empty() const { return size == 0; }
};
int main() {
IntStack st;
for (int i = 1; i <= 5; i++) {
std::cout << "push " << i * 10 << std::endl;
st.push(i * 10);
}
std::cout << "Popping: ";
while (!st.empty()) {
std::cout << st.top() << " ";
st.pop();
}
std::cout << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Doubling the capacity means a resize happens only after 2, 4, 8, … pushes, which keeps the average cost of
push()constant (amortized O(1)). - The destructor releases the heap array automatically when
stgoes out of scope, so the user of the class never callsdelete. - Deleting the copy operations is a simple way to prevent shallow copies. The Rule of Five exercises later show how to implement them properly.
Exercise 13: Singly Linked List with Manual Memory Management
Practice Problem: Implement a singly linked list using struct Node and raw pointers. Support pushBack(), remove(value), and print(), and free every node in the destructor.
Expected Output:
List: 3 -> 7 -> 1 -> 9 -> 4 -> nullptr
After removing 3 and 9: 7 -> 1 -> 4 -> nullptr
Remove 42 found? false
+ Hint
- Each
Nodeholds anint valueand aNode* next. The list keeps aheadpointer. - To remove a node, find the node before it, link that node to the one after, then
deletethe removed node. Handle removing the head as a special case. - In the destructor, walk the list and delete nodes one by one, saving
nextbefore eachdelete.
+ Show Solution
#include <iostream>
struct Node {
int value;
Node* next;
Node(int v) : value(v), next(nullptr) {}
};
class LinkedList {
Node* head = nullptr;
public:
~LinkedList() {
Node* cur = head;
while (cur) {
Node* nxt = cur->next;
delete cur;
cur = nxt;
}
}
void pushBack(int v) {
Node* node = new Node(v);
if (!head) { head = node; return; }
Node* cur = head;
while (cur->next) cur = cur->next;
cur->next = node;
}
bool remove(int v) {
if (!head) return false;
if (head->value == v) {
Node* old = head;
head = head->next;
delete old;
return true;
}
Node* cur = head;
while (cur->next && cur->next->value != v) cur = cur->next;
if (!cur->next) return false;
Node* target = cur->next;
cur->next = target->next;
delete target;
return true;
}
void print() const {
for (Node* cur = head; cur; cur = cur->next)
std::cout << cur->value << " -> ";
std::cout << "nullptr" << std::endl;
}
};
int main() {
LinkedList list;
for (int v : {3, 7, 1, 9, 4}) list.pushBack(v);
std::cout << "List: ";
list.print();
list.remove(3); // head
list.remove(9); // middle
std::cout << "After removing 3 and 9: ";
list.print();
std::cout << "Remove 42 found? " << std::boolalpha << list.remove(42) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Each
new Nodecreates a separate heap allocation, and each one must have a matchingdelete. - The destructor stores
cur->nextinnxtbefore deletingcur, because reading a member afterdeleteis undefined behavior. remove()returnsboolso the caller knows whether the value was found.std::boolalphaprints it astrue/false.
Exercise 14: unique_ptr Basics and Ownership Transfer
Practice Problem: Create a class Book that prints a message in its constructor and destructor. Use std::unique_ptr and std::make_unique to create a book, transfer ownership to another pointer with std::move, and show that the original pointer becomes empty.
Expected Output:
Book created: Clean Code
Reading Clean Code
p1 is empty
p2 is not empty
Reading Clean Code
End of main
Book destroyed: Clean Code
+ Hint
- Include
<memory>and create the object withauto p1 = std::make_unique<Book>("...");. - A
unique_ptrcannot be copied, only moved:auto p2 = std::move(p1);. After the move,p1isnullptr.
+ Show Solution
#include <iostream>
#include <memory>
#include <string>
class Book {
std::string title;
public:
Book(const std::string& t) : title(t) {
std::cout << "Book created: " << title << std::endl;
}
~Book() {
std::cout << "Book destroyed: " << title << std::endl;
}
void read() const { std::cout << "Reading " << title << std::endl; }
};
int main() {
auto p1 = std::make_unique<Book>("Clean Code");
p1->read();
std::unique_ptr<Book> p2 = std::move(p1); // transfer ownership
std::cout << "p1 is " << (p1 ? "not empty" : "empty") << std::endl;
std::cout << "p2 is " << (p2 ? "not empty" : "empty") << std::endl;
p2->read();
std::cout << "End of main" << std::endl;
return 0; // p2 goes out of scope -> Book destroyed automatically
}Code language: C++ (cpp)
Explanation:
std::unique_ptrrepresents exclusive ownership. Exactly one pointer owns the object at a time.std::move(p1)turnsp1into an rvalue so the move constructor ofunique_ptrcan steal its pointer, leavingp1empty.- No
deleteis written anywhere. The destructor message appears after “End of main” becausep2is destroyed whenmain()returns.
Exercise 15: Vector of unique_ptr
Practice Problem: Store several Sensor objects in a std::vector<std::unique_ptr<Sensor>>. Print each sensor’s reading, then remove the second sensor with erase() and observe that its destructor runs immediately.
Expected Output:
All sensors:
Temp: 22.5
Humidity: 61
Pressure: 1013.2
Erasing second sensor...
~Sensor(Humidity)
Remaining sensors:
Temp: 22.5
Pressure: 1013.2
Leaving main...
~Sensor(Temp)
~Sensor(Pressure)
+ Hint
- Use
sensors.push_back(std::make_unique<Sensor>(...)). The temporary returned bymake_uniqueis moved into the vector. - Iterate with
for (const auto& s : sensors). Using a reference is required becauseunique_ptrcannot be copied.
+ Show Solution
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class Sensor {
std::string name;
double reading;
public:
Sensor(std::string n, double r) : name(std::move(n)), reading(r) {}
~Sensor() { std::cout << " ~Sensor(" << name << ")" << std::endl; }
void report() const { std::cout << name << ": " << reading << std::endl; }
};
int main() {
std::vector<std::unique_ptr<Sensor>> sensors;
sensors.push_back(std::make_unique<Sensor>("Temp", 22.5));
sensors.push_back(std::make_unique<Sensor>("Humidity", 61.0));
sensors.push_back(std::make_unique<Sensor>("Pressure", 1013.2));
std::cout << "All sensors:" << std::endl;
for (const auto& s : sensors) s->report();
std::cout << "Erasing second sensor..." << std::endl;
sensors.erase(sensors.begin() + 1);
std::cout << "Remaining sensors:" << std::endl;
for (const auto& s : sensors) s->report();
std::cout << "Leaving main..." << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The vector owns the
unique_ptrs, and eachunique_ptrowns aSensor. Destroying an element destroys the object it points to. erase()destroys the removedunique_ptr, so “~Sensor(Humidity)” is printed right away, before the remaining sensors are listed.- When
main()ends, the vector is destroyed and the remaining sensors are cleaned up automatically. There are no leaks even though objects live on the heap.
Exercise 16: shared_ptr and Reference Counting
Practice Problem: Demonstrate shared ownership with std::shared_ptr. Create one object, share it between several pointers (including one inside an inner scope), and print use_count() at each step to show when the object is destroyed.
Expected Output:
Config loaded
Count after a: 1
Count after b = a: 2
Count inside block: 3
Count after block: 2
Count after a.reset(): 1
Config released
b is empty
+ Hint
- Create the object with
std::make_shared<T>(). Copying ashared_ptrincreases the reference count. - When a
shared_ptrgoes out of scope or isreset(), the count decreases. The object is deleted when the count reaches 0.
+ Show Solution
#include <iostream>
#include <memory>
struct Config {
Config() { std::cout << "Config loaded" << std::endl; }
~Config() { std::cout << "Config released" << std::endl; }
};
int main() {
std::shared_ptr<Config> a = std::make_shared<Config>();
std::cout << "Count after a: " << a.use_count() << std::endl;
std::shared_ptr<Config> b = a; // copy -> shared ownership
std::cout << "Count after b = a: " << a.use_count() << std::endl;
{
std::shared_ptr<Config> c = b;
std::cout << "Count inside block: " << a.use_count() << std::endl;
} // c destroyed here
std::cout << "Count after block: " << a.use_count() << std::endl;
a.reset(); // a gives up ownership
std::cout << "Count after a.reset(): " << b.use_count() << std::endl;
b.reset(); // last owner -> object deleted
std::cout << "b is " << (b ? "valid" : "empty") << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- All copies of a
shared_ptrpoint to the same control block, which stores the reference count. - The count goes 1 → 2 → 3 → 2 → 1 as owners are added and removed.
- “Config released” is printed at the exact moment the last owner (
b) callsreset(), not at the end ofmain().
Exercise 17: Break a Cyclic Reference with weak_ptr
Practice Problem: Create Parent and Child classes that point to each other. Show that using shared_ptr in both directions would leak, and fix it by making the child’s back-pointer a std::weak_ptr. Use lock() to access the parent from the child.
Expected Output:
Leo says hi to parent Anna
Parent use_count: 1
Child use_count: 2
Parent Anna destroyed
Child Leo destroyed
Scope ended, both objects were freed.
+ Hint
- If both objects hold a
shared_ptrto each other, their counts never reach 0, so neither destructor runs. - A
weak_ptrobserves an object without owning it. Calllock()to get a temporaryshared_ptrthat is empty if the object is gone.
+ Show Solution
#include <iostream>
#include <memory>
#include <string>
struct Parent;
struct Child {
std::string name;
std::weak_ptr<Parent> parent; // non-owning back reference
Child(std::string n) : name(std::move(n)) {}
~Child() { std::cout << "Child " << name << " destroyed" << std::endl; }
void greet() const;
};
struct Parent {
std::string name;
std::shared_ptr<Child> child; // owning reference
Parent(std::string n) : name(std::move(n)) {}
~Parent() { std::cout << "Parent " << name << " destroyed" << std::endl; }
};
void Child::greet() const {
if (auto p = parent.lock()) {
std::cout << name << " says hi to parent " << p->name << std::endl;
} else {
std::cout << name << " has no parent anymore" << std::endl;
}
}
int main() {
{
auto mom = std::make_shared<Parent>("Anna");
auto kid = std::make_shared<Child>("Leo");
mom->child = kid;
kid->parent = mom;
kid->greet();
std::cout << "Parent use_count: " << mom.use_count() << std::endl;
std::cout << "Child use_count: " << kid.use_count() << std::endl;
}
std::cout << "Scope ended, both objects were freed." << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The parent’s
use_count()is 1 because the child’sweak_ptrdoes not add to the count. The child’s count is 2 (kidandmom->child). - When the scope ends,
momdrops to 0 and is destroyed, which then releases the child. Both destructor messages prove there is no leak. parent.lock()is the safe way to use aweak_ptr. It returns an empty pointer if the parent has already been destroyed.
Exercise 18: unique_ptr with a Custom Deleter
Practice Problem: Some resources are not released with delete (for example a C FILE* is closed with fclose). Write a program that manages a FILE* with std::unique_ptr and a custom deleter, writes two lines to a file, and lets the deleter close it automatically.
Expected Output:
Lines written
Custom deleter: file closed
Read: First log line
Read: Second log line
Custom deleter: file closed
+ Hint
- The deleter type is the second template argument:
std::unique_ptr<FILE, decltype(&closeFile)>. - Pass the deleter function as the second constructor argument:
FilePtr fp(fopen(...), &closeFile);.
+ Show Solution
#include <cstdio>
#include <iostream>
#include <memory>
void closeFile(FILE* f) {
if (f) {
std::fclose(f);
std::cout << "Custom deleter: file closed" << std::endl;
}
}
using FilePtr = std::unique_ptr<FILE, decltype(&closeFile)>;
int main() {
{
FilePtr fp(std::fopen("log.txt", "w"), &closeFile);
if (!fp) {
std::cout << "Could not open file" << std::endl;
return 1;
}
std::fprintf(fp.get(), "First log line\n");
std::fprintf(fp.get(), "Second log line\n");
std::cout << "Lines written" << std::endl;
} // closeFile() is called here
// Read the file back to confirm
FilePtr in(std::fopen("log.txt", "r"), &closeFile);
char buffer[64];
while (std::fgets(buffer, sizeof(buffer), in.get())) {
std::cout << "Read: " << buffer;
}
return 0;
}Code language: C++ (cpp)
Explanation:
fp.get()returns the rawFILE*so it can be passed to C functions such asfprintf.- When the
unique_ptrgoes out of scope it callscloseFile()instead ofdelete, so the file is always closed, even on earlyreturn. - This technique turns any C-style handle (sockets, database connections, library handles) into an RAII object.
Exercise 19: RAII Scope Guard
Practice Problem: Write an RAII class ScopeLogger that prints “Enter <name>” in its constructor and “Exit <name>” in its destructor. Use it in a function with an early return and in nested scopes to show that cleanup always happens.
Given:
int data[] = {4, 8, 15, 16, 23, 42};
int target = 15;Code language: Python (python)
Expected Output:
Enter main
Enter inner block
Enter findIndex
found at index 2
Exit findIndex
Exit inner block
Back in main
Exit main
+ Hint
- RAII = Resource Acquisition Is Initialization: acquire in the constructor, release in the destructor.
- Local objects are destroyed in reverse order of construction whenever a scope ends, including through
return.
+ Show Solution
#include <iostream>
#include <string>
class ScopeLogger {
std::string name;
public:
explicit ScopeLogger(std::string n) : name(std::move(n)) {
std::cout << "Enter " << name << std::endl;
}
~ScopeLogger() {
std::cout << "Exit " << name << std::endl;
}
};
int findIndex(const int* arr, int n, int target) {
ScopeLogger log("findIndex");
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
std::cout << " found at index " << i << std::endl;
return i; // destructor still runs
}
}
return -1;
}
int main() {
ScopeLogger outer("main");
int data[] = {4, 8, 15, 16, 23, 42};
{
ScopeLogger inner("inner block");
findIndex(data, 6, 15);
}
std::cout << "Back in main" << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The destructor of
logruns whenfindIndex()returns early, so “Exit findIndex” is printed without any extra code. - Nested scopes unwind in reverse order:
findIndex, theninner block, and finallymain. - Standard classes such as
std::lock_guard,std::fstream, and smart pointers all follow this same RAII pattern.
Exercise 20: Bank Account Class with Encapsulation
Practice Problem: Create a BankAccount class with private data members (owner, balance) and public methods deposit(), withdraw(), and getBalance(). Reject negative deposits and withdrawals larger than the balance.
Given:
BankAccount acc("Alice", 500);
// deposit 250, deposit -40, withdraw 1000, withdraw 300Code language: Python (python)
Expected Output:
Deposited 250
Invalid deposit amount: -40
Insufficient funds to withdraw 1000
Withdrew 300
Alice's balance: 450
+ Hint
- Keep
balanceprivate so it can only change through methods that validate the input. - Make
withdraw()returnboolto tell the caller whether the operation succeeded.
+ Show Solution
#include <iostream>
#include <string>
class BankAccount {
private:
std::string owner;
double balance;
public:
BankAccount(const std::string& name, double initial)
: owner(name), balance(initial > 0 ? initial : 0) {}
bool deposit(double amount) {
if (amount <= 0) {
std::cout << "Invalid deposit amount: " << amount << std::endl;
return false;
}
balance += amount;
std::cout << "Deposited " << amount << std::endl;
return true;
}
bool withdraw(double amount) {
if (amount > balance) {
std::cout << "Insufficient funds to withdraw " << amount << std::endl;
return false;
}
balance -= amount;
std::cout << "Withdrew " << amount << std::endl;
return true;
}
double getBalance() const { return balance; }
const std::string& getOwner() const { return owner; }
};
int main() {
BankAccount acc("Alice", 500);
acc.deposit(250);
acc.deposit(-40);
acc.withdraw(1000);
acc.withdraw(300);
std::cout << acc.getOwner() << "'s balance: " << acc.getBalance() << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Encapsulation hides the data and exposes only safe operations. Code outside the class cannot write
acc.balance = -999;. - Getter methods are marked
constbecause they do not modify the object, so they can also be called onconstaccounts. - The constructor uses a member initializer list, which initializes members directly instead of assigning them later.
Exercise 21: Constructor Overloading and Delegating Constructors
Practice Problem: Create a Rectangle class with three constructors: a default constructor (1 x 1), a one-argument constructor that makes a square, and a two-argument constructor. Use delegating constructors so all of them call the two-argument version.
Given:
Rectangle r1;
Rectangle r2(5);
Rectangle r3(4, 2.5);Code language: Python (python)
Expected Output:
Rectangle(1, 1) created
Rectangle(5, 5) created
Rectangle(4, 2.5) created
r1 area: 1, perimeter: 4
r2 area: 25, perimeter: 20
r3 area: 10, perimeter: 13
+ Hint
- A delegating constructor calls another constructor of the same class in its initializer list:
Rectangle() : Rectangle(1, 1) {}. - Put the printing or validation logic only in the main constructor so it is not repeated.
+ Show Solution
#include <iostream>
class Rectangle {
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {
std::cout << "Rectangle(" << width << ", " << height << ") created" << std::endl;
}
Rectangle() : Rectangle(1, 1) {} // default
explicit Rectangle(double side) : Rectangle(side, side) {} // square
double area() const { return width * height; }
double perimeter() const { return 2 * (width + height); }
};
int main() {
Rectangle r1;
Rectangle r2(5);
Rectangle r3(4, 2.5);
std::cout << "r1 area: " << r1.area() << ", perimeter: " << r1.perimeter() << std::endl;
std::cout << "r2 area: " << r2.area() << ", perimeter: " << r2.perimeter() << std::endl;
std::cout << "r3 area: " << r3.area() << ", perimeter: " << r3.perimeter() << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Constructor overloading lets objects be created in different ways, and the compiler picks the version that matches the arguments.
- Delegating constructors (C++11) remove duplicated code: every path ends in the two-argument constructor, which is why each object prints one creation message.
expliciton the single-argument constructor prevents accidental implicit conversions such asRectangle r = 5;.
Exercise 22: Static Members: Count Live Objects
Practice Problem: Create a class Player that uses a static data member to track how many players have been created in total and how many are currently alive. Provide a static member function to print the counts.
Expected Output:
Created: 0, Alive: 0
Created: 2, Alive: 2
Created: 4, Alive: 4
Created: 4, Alive: 2
+ Hint
- A static member is shared by all objects of the class. Declare it inside the class and, since C++17, you can initialize it inline with
inline static int count = 0;. - Increase the counters in the constructor and decrease the “alive” counter in the destructor.
+ Show Solution
#include <iostream>
#include <string>
class Player {
std::string name;
inline static int totalCreated = 0;
inline static int alive = 0;
public:
Player(std::string n) : name(std::move(n)) {
totalCreated++;
alive++;
}
~Player() { alive--; }
static void printStats() {
std::cout << "Created: " << totalCreated << ", Alive: " << alive << std::endl;
}
};
int main() {
Player::printStats();
Player p1("Ava");
Player p2("Ben");
Player::printStats();
{
Player p3("Cleo");
Player p4("Dan");
Player::printStats();
} // p3 and p4 destroyed here
Player::printStats();
return 0;
}Code language: C++ (cpp)
Explanation:
- Static members belong to the class itself, not to any single object, so they are accessed with
Player::printStats(). - A static member function has no
thispointer and can only access static members directly. - When the inner block ends,
p3andp4are destroyed, soalivedrops from 4 to 2 whiletotalCreatedstays at 4.
Exercise 23: Inheritance: Employee and Manager
Practice Problem: Create a base class Employee with a name and base salary, and a derived class Manager that adds a bonus. Override a virtual function calculatePay() in Manager and call the base class version inside it.
Given:
Employee e("Ravi", 4000);
Manager m("Sara", 6000, 1500);Code language: Python (python)
Expected Output:
Employee Ravi earns 4000
Manager Sara earns 7500
+ Hint
- The derived class constructor must call the base constructor in its initializer list:
Manager(...) : Employee(name, salary), bonus(b) {}. - Inside the override, call the base version with
Employee::calculatePay()to reuse its logic.
+ Show Solution
#include <iostream>
#include <string>
class Employee {
protected:
std::string name;
double baseSalary;
public:
Employee(std::string n, double s) : name(std::move(n)), baseSalary(s) {}
virtual ~Employee() = default;
virtual double calculatePay() const { return baseSalary; }
virtual std::string role() const { return "Employee"; }
void printPay() const {
std::cout << role() << " " << name << " earns " << calculatePay() << std::endl;
}
};
class Manager : public Employee {
double bonus;
public:
Manager(std::string n, double s, double b) : Employee(std::move(n), s), bonus(b) {}
double calculatePay() const override {
return Employee::calculatePay() + bonus; // reuse base logic
}
std::string role() const override { return "Manager"; }
};
int main() {
Employee e("Ravi", 4000);
Manager m("Sara", 6000, 1500);
e.printPay();
m.printPay();
return 0;
}Code language: C++ (cpp)
Explanation:
protectedmembers are accessible inside derived classes but still hidden from outside code.printPay()is defined only once in the base class, yet it calls the correctrole()andcalculatePay()for each object because they arevirtual.- The
overridekeyword asks the compiler to check that the function really overrides a base class virtual function.
Exercise 24: Abstract Class and Runtime Polymorphism
Practice Problem: Create an abstract class Shape with pure virtual functions area() and name(). Derive Circle, Rectangle, and Triangle. Store them in a std::vector<std::unique_ptr<Shape>> and print each area and the total area.
Given:
Circle(3), Rectangle(4, 5), Triangle(6, 2)Code language: Python (python)
Expected Output:
Circle area: 28.27
Rectangle area: 20.00
Triangle area: 6.00
Total area: 54.27
+ Hint
- A pure virtual function is declared with
= 0, for examplevirtual double area() const = 0;. A class with one cannot be instantiated. - Use
std::fixedandstd::setprecision(2)from<iomanip>for neat output.
+ Show Solution
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class Shape {
public:
virtual ~Shape() = default;
virtual double area() const = 0;
virtual std::string name() const = 0;
};
class Circle : public Shape {
double r;
public:
explicit Circle(double radius) : r(radius) {}
double area() const override { return 3.14159265358979 * r * r; }
std::string name() const override { return "Circle"; }
};
class Rectangle : public Shape {
double w, h;
public:
Rectangle(double width, double height) : w(width), h(height) {}
double area() const override { return w * h; }
std::string name() const override { return "Rectangle"; }
};
class Triangle : public Shape {
double b, h;
public:
Triangle(double base, double height) : b(base), h(height) {}
double area() const override { return 0.5 * b * h; }
std::string name() const override { return "Triangle"; }
};
int main() {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(3));
shapes.push_back(std::make_unique<Rectangle>(4, 5));
shapes.push_back(std::make_unique<Triangle>(6, 2));
std::cout << std::fixed << std::setprecision(2);
double total = 0;
for (const auto& s : shapes) {
std::cout << std::setw(10) << std::left << s->name() << " area: " << s->area() << std::endl;
total += s->area();
}
std::cout << "Total area: " << total << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The loop only knows about
Shape, yet each call goes to the right derived implementation. This is runtime polymorphism through the virtual table. Shapehas a virtual destructor, so deleting a derived object through aShapepointer (done here byunique_ptr) calls the correct destructor.- Adding a new shape only requires a new class. The loop in
main()does not need to change, which follows the open/closed principle.
Exercise 25: Why Destructors Must Be Virtual
Practice Problem: Write two class hierarchies: one where the base class destructor is not virtual and one where it is. Delete a derived object through a base pointer for the virtual version and print which destructors run, then show the normal destruction order for the non-virtual version.
Expected Output:
Deleting through BaseVirtual*:
~DerivedB (releases resources)
~BaseVirtual
Correct order for a stack object of DerivedA:
~DerivedA (releases resources)
~BaseNoVirtual
Rule: if a class has virtual functions or is meant to be a base class, give it a virtual destructor.
+ Hint
- Print a message in every constructor and destructor.
- Deleting a derived object through a base pointer whose destructor is not virtual is undefined behavior. In practice, only the base destructor runs, so the derived part is never cleaned up.
+ Show Solution
#include <iostream>
class BaseNoVirtual {
public:
~BaseNoVirtual() { std::cout << " ~BaseNoVirtual" << std::endl; }
};
class DerivedA : public BaseNoVirtual {
public:
~DerivedA() { std::cout << " ~DerivedA (releases resources)" << std::endl; }
};
class BaseVirtual {
public:
virtual ~BaseVirtual() { std::cout << " ~BaseVirtual" << std::endl; }
};
class DerivedB : public BaseVirtual {
public:
~DerivedB() override { std::cout << " ~DerivedB (releases resources)" << std::endl; }
};
int main() {
std::cout << "Deleting through BaseVirtual*:" << std::endl;
BaseVirtual* good = new DerivedB();
delete good;
std::cout << "Correct order for a stack object of DerivedA:" << std::endl;
{
DerivedA a;
}
std::cout << "Rule: if a class has virtual functions or is meant to be a base class,"
<< " give it a virtual destructor." << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- With a virtual destructor,
delete good;runs~DerivedBfirst and then~BaseVirtual, which is the correct order: derived first, base last. - The program does not actually delete a
DerivedAthrough aBaseNoVirtual*, because that is undefined behavior. A stack object ofDerivedAis used instead to show the normal destruction order. - Smart pointers do not fix this problem on their own. A
std::unique_ptr<Base>holding a derived object still needs a virtual destructor inBase.
Exercise 26: Friend Function: Distance Between Two Points
Practice Problem: Create a Point class with private x and y. Declare a friend function distance(const Point&, const Point&) that reads the private members directly, and a friend operator<< to print a point.
Given:
Point p1(1, 2), p2(4, 6);Code language: Python (python)
Expected Output:
p1 = (1, 2), p2 = (4, 6)
Distance: 5
+ Hint
- Inside the class write
friend double distance(const Point& a, const Point& b);. The function is defined outside the class and is not a member. - Use
std::sqrtfrom<cmath>for the Euclidean distance formula.
+ Show Solution
#include <cmath>
#include <iostream>
class Point {
double x, y;
public:
Point(double x, double y) : x(x), y(y) {}
friend double distance(const Point& a, const Point& b);
friend std::ostream& operator<<(std::ostream& os, const Point& p);
};
double distance(const Point& a, const Point& b) {
double dx = a.x - b.x; // private access allowed
double dy = a.y - b.y;
return std::sqrt(dx * dx + dy * dy);
}
std::ostream& operator<<(std::ostream& os, const Point& p) {
return os << "(" << p.x << ", " << p.y << ")";
}
int main() {
Point p1(1, 2), p2(4, 6);
std::cout << "p1 = " << p1 << ", p2 = " << p2 << std::endl;
std::cout << "Distance: " << distance(p1, p2) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- A
frienddeclaration gives a non-member function access to the private members of the class. distance()is symmetric (both points are treated the same way), which is a good reason to make it a free function instead of a member.- The stream operator must be a non-member because the left operand is
std::ostream, notPoint. Making it a friend lets it print private data.
Exercise 27: Composition: Car Has an Engine
Practice Problem: Model a Car that contains an Engine object as a member (composition). Print messages from both constructors and destructors to show the order in which the parts are created and destroyed.
Given:
Car car("Roadster", 300);Code language: Python (python)
Expected Output:
Engine(300 hp) built
Car Roadster assembled
Engine with 300 hp started
Roadster is driving
Car Roadster scrapped
Engine removed
+ Hint
- Composition means “has-a”: the
Engineis a data member ofCar, not a base class. - Member objects are constructed before the body of the owner’s constructor runs, and destroyed after the owner’s destructor body.
+ Show Solution
#include <iostream>
#include <string>
class Engine {
int horsepower;
public:
explicit Engine(int hp) : horsepower(hp) {
std::cout << "Engine(" << horsepower << " hp) built" << std::endl;
}
~Engine() { std::cout << "Engine removed" << std::endl; }
void start() const { std::cout << "Engine with " << horsepower << " hp started" << std::endl; }
};
class Car {
std::string model;
Engine engine; // Car HAS-AN Engine
public:
Car(std::string m, int hp) : model(std::move(m)), engine(hp) {
std::cout << "Car " << model << " assembled" << std::endl;
}
~Car() { std::cout << "Car " << model << " scrapped" << std::endl; }
void drive() const {
engine.start();
std::cout << model << " is driving" << std::endl;
}
};
int main() {
Car car("Roadster", 300);
car.drive();
return 0;
}Code language: C++ (cpp)
Explanation:
- The
Engineis created first (in the initializer list) and theCarconstructor body runs afterward. - Destruction happens in reverse: the
Cardestructor body runs first, then theEnginemember is destroyed. - Prefer composition over inheritance when one object is simply a part of another. It keeps classes loosely coupled.
Exercise 28: Diamond Problem and Virtual Inheritance
Practice Problem: Create a diamond hierarchy: Device → Printer and Scanner → Copier. Use virtual inheritance so that Copier contains only one Device sub-object, and show that the Device constructor runs only once.
Given:
Copier c("CP-100");Code language: Python (python)
Expected Output:
Device(CP-100) constructed
Printer part ready
Scanner part ready
Copier ready
CP-100 powered on
CP-100 scanning
CP-100 printing
+ Hint
- Write
class Printer : virtual public Deviceandclass Scanner : virtual public Device. - With virtual inheritance, the most-derived class (
Copier) is responsible for calling theDeviceconstructor directly.
+ Show Solution
#include <iostream>
#include <string>
class Device {
protected:
std::string id;
public:
explicit Device(std::string i) : id(std::move(i)) {
std::cout << "Device(" << id << ") constructed" << std::endl;
}
void powerOn() const { std::cout << id << " powered on" << std::endl; }
};
class Printer : virtual public Device {
public:
Printer() : Device("unused") { std::cout << "Printer part ready" << std::endl; }
void print() const { std::cout << id << " printing" << std::endl; }
};
class Scanner : virtual public Device {
public:
Scanner() : Device("unused") { std::cout << "Scanner part ready" << std::endl; }
void scan() const { std::cout << id << " scanning" << std::endl; }
};
class Copier : public Printer, public Scanner {
public:
Copier(const std::string& i) : Device(i) {
std::cout << "Copier ready" << std::endl;
}
void copy() const {
scan();
print();
}
};
int main() {
Copier c("CP-100");
c.powerOn(); // not ambiguous: only one Device sub-object
c.copy();
return 0;
}Code language: C++ (cpp)
Explanation:
- Without
virtual, aCopierwould contain two separateDeviceobjects, andc.powerOn()would be an ambiguous call. - Because
Deviceis a virtual base, it is constructed exactly once, byCopier. TheDevice("unused")calls inPrinterandScannerare ignored, so the id is “CP-100”. - Virtual bases are always constructed first, before the non-virtual bases
PrinterandScanner.
Exercise 29: const Member Functions and mutable
Practice Problem: Create a class Document with a const getter getText() that also counts how many times the text has been read. Use a mutable counter so it can be updated inside a const function, and call the getter on a const object.
Expected Output:
Text: Read me first
Text: Read me first
readme was read 2 times
Text: Final
notes was read 1 times
+ Hint
- A member function marked
constpromises not to change the object’s observable state. - A member declared
mutablecan still be modified inside aconstmember function. It is meant for internal details such as caches, counters, or mutexes.
+ Show Solution
#include <iostream>
#include <string>
class Document {
std::string text;
mutable int readCount = 0;
public:
explicit Document(std::string t) : text(std::move(t)) {}
const std::string& getText() const {
++readCount; // allowed because readCount is mutable
return text;
}
void setText(const std::string& t) { text = t; } // non-const
int reads() const { return readCount; }
};
void show(const Document& doc) {
std::cout << "Text: " << doc.getText() << std::endl;
// doc.setText("x"); // error: cannot call non-const function on const object
}
int main() {
const Document readme("Read me first");
show(readme);
show(readme);
std::cout << "readme was read " << readme.reads() << " times" << std::endl;
Document notes("Draft");
notes.setText("Final");
show(notes);
std::cout << "notes was read " << notes.reads() << " times" << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- A
constobject (or aconstreference such as the parameter ofshow()) can call onlyconstmember functions. getText()returnsconst std::string&, which avoids a copy while still preventing the caller from changing the text.mutableis useful when a change is invisible to the user of the class. Do not use it to bypassconstfor real data.
Exercise 30: Complex Number Class with Arithmetic Operators
Practice Problem: Create a Complex class and overload the +, -, *, and == operators, plus << for printing in the form a + bi.
Given:
Complex a(3, 2), b(1, -4);Code language: Python (python)
Expected Output:
a = 3 + 2i
b = 1 - 4i
a + b = 4 - 2i
a - b = 2 + 6i
a * b = 11 - 10i
a == Complex(3, 2): true
a + 5 = 8 + 2i
+ Hint
- The product of (a + bi) and (c + di) is (ac – bd) + (ad + bc)i.
- Implement binary operators as non-member functions that take both operands by
constreference and return a new object by value.
+ Show Solution
#include <iostream>
class Complex {
double re, im;
public:
Complex(double r = 0, double i = 0) : re(r), im(i) {}
double real() const { return re; }
double imag() const { return im; }
};
Complex operator+(const Complex& a, const Complex& b) {
return Complex(a.real() + b.real(), a.imag() + b.imag());
}
Complex operator-(const Complex& a, const Complex& b) {
return Complex(a.real() - b.real(), a.imag() - b.imag());
}
Complex operator*(const Complex& a, const Complex& b) {
return Complex(a.real() * b.real() - a.imag() * b.imag(),
a.real() * b.imag() + a.imag() * b.real());
}
bool operator==(const Complex& a, const Complex& b) {
return a.real() == b.real() && a.imag() == b.imag();
}
std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real() << (c.imag() < 0 ? " - " : " + ")
<< (c.imag() < 0 ? -c.imag() : c.imag()) << "i";
return os;
}
int main() {
Complex a(3, 2), b(1, -4);
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
std::cout << "a + b = " << a + b << std::endl;
std::cout << "a - b = " << a - b << std::endl;
std::cout << "a * b = " << a * b << std::endl;
std::cout << std::boolalpha << "a == Complex(3, 2): " << (a == Complex(3, 2)) << std::endl;
std::cout << "a + 5 = " << a + 5 << std::endl; // 5 converts to Complex(5, 0)
return 0;
}Code language: C++ (cpp)
Explanation:
- Non-member operators treat both operands equally, so
a + 5works because the constructor converts5intoComplex(5, 0). operator<<returns the stream by reference so calls can be chained:std::cout << a << b.- The printing operator shows a minus sign for negative imaginary parts, so
1 - 4iis printed instead of1 + -4i.
Exercise 31: Fraction Class with Automatic Reduction
Practice Problem: Create a Fraction class that always stores fractions in lowest terms with a positive denominator. Overload +, *, ==, <, and <<. Add 1/2 + 1/3 and multiply 3/4 * 2/9.
Given:
Fraction a(1, 2), b(1, 3), c(3, 4), d(2, 9);Code language: Python (python)
Expected Output:
1/2 + 1/3 = 5/6
3/4 * 2/9 = 1/6
6/-8 is stored as -3/4
2/4 == 1/2: true
1/3 < 1/2: true
+ Hint
- Use
std::gcdfrom<numeric>(C++17) to reduce numerator and denominator in the constructor. - To compare a/b < c/d without floating point, compare a*d < c*b (denominators are positive).
+ Show Solution
#include <iostream>
#include <numeric>
#include <stdexcept>
class Fraction {
long num, den;
void normalize() {
if (den == 0) throw std::invalid_argument("denominator cannot be zero");
if (den < 0) { num = -num; den = -den; }
long g = std::gcd(num, den);
if (g != 0) { num /= g; den /= g; }
}
public:
Fraction(long n = 0, long d = 1) : num(n), den(d) { normalize(); }
friend Fraction operator+(const Fraction& a, const Fraction& b) {
return Fraction(a.num * b.den + b.num * a.den, a.den * b.den);
}
friend Fraction operator*(const Fraction& a, const Fraction& b) {
return Fraction(a.num * b.num, a.den * b.den);
}
friend bool operator==(const Fraction& a, const Fraction& b) {
return a.num == b.num && a.den == b.den;
}
friend bool operator<(const Fraction& a, const Fraction& b) {
return a.num * b.den < b.num * a.den;
}
friend std::ostream& operator<<(std::ostream& os, const Fraction& f) {
return os << f.num << "/" << f.den;
}
};
int main() {
Fraction a(1, 2), b(1, 3), c(3, 4), d(2, 9);
std::cout << a << " + " << b << " = " << a + b << std::endl;
std::cout << c << " * " << d << " = " << c * d << std::endl;
std::cout << "6/-8 is stored as " << Fraction(6, -8) << std::endl;
std::cout << std::boolalpha;
std::cout << "2/4 == 1/2: " << (Fraction(2, 4) == a) << std::endl;
std::cout << "1/3 < 1/2: " << (b < a) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Reducing in the constructor means every
Fractionis always in canonical form, sooperator==can simply compare the members. - Defining the operators as friend functions inside the class (hidden friends) keeps them close to the class and gives them access to private data.
- Invalid fractions are rejected by throwing
std::invalid_argument, so an object with a zero denominator can never exist.
Exercise 32: Vector2D: Unary, Compound, and Scalar Operators
Practice Problem: Create a Vector2D class and overload unary minus (-v), compound assignment (+=, *= with a scalar), binary +, and scalar multiplication in both orders (v * 2 and 2 * v). Also add a length() method.
Given:
Vector2D a(3, 4), b(1, -2);Code language: Python (python)
Expected Output:
a = (3, 4), |a| = 5
-a = (-3, -4)
a + b = (4, 2)
a * 2 = (6, 8)
3 * b = (3, -6)
after a += b, a = (4, 2)
after a *= 0.5, a = (2, 1)
+ Hint
- Implement
+=as a member that returns*thisby reference, then implement+in terms of+=. 2 * vneeds a non-member function because the left operand is adouble, not aVector2D.
+ Show Solution
#include <cmath>
#include <iostream>
class Vector2D {
public:
double x, y;
Vector2D(double x = 0, double y = 0) : x(x), y(y) {}
Vector2D operator-() const { return Vector2D(-x, -y); }
Vector2D& operator+=(const Vector2D& o) {
x += o.x; y += o.y;
return *this;
}
Vector2D& operator*=(double k) {
x *= k; y *= k;
return *this;
}
double length() const { return std::sqrt(x * x + y * y); }
};
Vector2D operator+(Vector2D a, const Vector2D& b) { return a += b; }
Vector2D operator*(Vector2D v, double k) { return v *= k; }
Vector2D operator*(double k, Vector2D v) { return v *= k; }
std::ostream& operator<<(std::ostream& os, const Vector2D& v) {
return os << "(" << v.x << ", " << v.y << ")";
}
int main() {
Vector2D a(3, 4), b(1, -2);
std::cout << "a = " << a << ", |a| = " << a.length() << std::endl;
std::cout << "-a = " << -a << std::endl;
std::cout << "a + b = " << a + b << std::endl;
std::cout << "a * 2 = " << a * 2 << std::endl;
std::cout << "3 * b = " << 3 * b << std::endl;
a += b;
std::cout << "after a += b, a = " << a << std::endl;
a *= 0.5;
std::cout << "after a *= 0.5, a = " << a << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Compound operators modify the object and return a reference to it, which matches the behavior of built-in types (
(a += b) += cworks). - The binary
+takes its first parameter by value, modifies that copy with+=, and returns it. This is a common idiom that avoids duplicated code. - Two versions of
operator*make scalar multiplication commutative, just like in mathematics.
Exercise 33: Bounds-Checked Array with operator[]
Practice Problem: Create a fixed-size class SafeArray that overloads operator[] in both a const and a non-const version. Throw std::out_of_range when the index is invalid.
Expected Output:
11 22 33 44 55
Error: Index 7 is out of range
+ Hint
- The non-const version returns
int&so it can be used on the left side of an assignment:arr[2] = 10;. - The const version returns
const int&(orint) so it works on const objects but does not allow modification.
+ Show Solution
#include <iostream>
#include <stdexcept>
#include <string>
class SafeArray {
static const int SIZE = 5;
int data[SIZE] = {0};
void check(int i) const {
if (i < 0 || i >= SIZE)
throw std::out_of_range("Index " + std::to_string(i) + " is out of range");
}
public:
int& operator[](int i) { // read/write access
check(i);
return data[i];
}
const int& operator[](int i) const { // read-only access
check(i);
return data[i];
}
int size() const { return SIZE; }
};
void printAll(const SafeArray& a) {
for (int i = 0; i < a.size(); i++) std::cout << a[i] << " "; // const version
std::cout << std::endl;
}
int main() {
SafeArray arr;
for (int i = 0; i < arr.size(); i++) arr[i] = (i + 1) * 11; // non-const version
printAll(arr);
try {
arr[7] = 100;
} catch (const std::out_of_range& e) {
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Returning a reference from
operator[]is what allows assignments such asarr[i] = valueto change the stored element. - The compiler chooses the
constoverload when the object isconst, as insideprintAll(). - Throwing an exception is much safer than silently reading or writing memory outside the array.
Exercise 34: Prefix and Postfix Increment Operators
Practice Problem: Create a Counter class and overload both prefix (++c) and postfix (c++) increment, plus prefix and postfix decrement. Show the difference in their return values.
Given:
Counter c(5);Code language: Python (python)
Expected Output:
++c returned 6, c is now 6
c++ returned 6, c is now 7
c-- returned 7, c is now 6
--c returned 5, c is now 5
+ Hint
- The postfix version takes a dummy
intparameter:Counter operator++(int). - Prefix returns a reference to the updated object. Postfix saves a copy of the old value, increments, and returns the copy.
+ Show Solution
#include <iostream>
class Counter {
int value;
public:
explicit Counter(int v = 0) : value(v) {}
Counter& operator++() { // prefix
++value;
return *this;
}
Counter operator++(int) { // postfix
Counter old = *this;
++value;
return old;
}
Counter& operator--() { --value; return *this; }
Counter operator--(int) { Counter old = *this; --value; return old; }
int get() const { return value; }
};
int main() {
Counter c(5);
Counter a = ++c;
std::cout << "++c returned " << a.get() << ", c is now " << c.get() << std::endl;
Counter b = c++;
std::cout << "c++ returned " << b.get() << ", c is now " << c.get() << std::endl;
Counter d = c--;
std::cout << "c-- returned " << d.get() << ", c is now " << c.get() << std::endl;
Counter e = --c;
std::cout << "--c returned " << e.get() << ", c is now " << c.get() << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The
intparameter in the postfix version is never used. It only exists so the compiler can tell the two overloads apart. - Prefix returns
Counter&(no copy), while postfix must return the old value by value, which makes it slightly more expensive. - This is why prefix
++itis usually preferred for iterators and other class types in loops.
Exercise 35: Function Call Operator: Polynomial Functor
Practice Problem: Create a class Polynomial that stores coefficients and overloads operator() so a polynomial object can be called like a function, for example p(2). Evaluate p(x) = 2x³ – 3x² + 4 at several points and use the object with std::transform.
Given:
p(x) = 2x^3 - 3x^2 + 4
std::vector<double> xs = {-1, 0.5, 3};Code language: Python (python)
Expected Output:
p(0) = 4
p(1) = 3
p(2) = 8
p(-1) = -1
p(0.5) = 3.5
p(3) = 31
+ Hint
- Store coefficients in a
std::vector<double>from the highest power to the constant term. - Use Horner’s method: start with
result = 0, and for each coefficient doresult = result * x + coef.
+ Show Solution
#include <algorithm>
#include <iostream>
#include <vector>
class Polynomial {
std::vector<double> coef; // highest degree first
public:
explicit Polynomial(std::vector<double> c) : coef(std::move(c)) {}
double operator()(double x) const {
double result = 0;
for (double c : coef) result = result * x + c; // Horner's method
return result;
}
};
int main() {
Polynomial p({2, -3, 0, 4}); // 2x^3 - 3x^2 + 0x + 4
std::cout << "p(0) = " << p(0) << std::endl;
std::cout << "p(1) = " << p(1) << std::endl;
std::cout << "p(2) = " << p(2) << std::endl;
std::vector<double> xs = {-1, 0.5, 3};
std::vector<double> ys(xs.size());
std::transform(xs.begin(), xs.end(), ys.begin(), p); // functor used as a callable
for (size_t i = 0; i < xs.size(); i++)
std::cout << "p(" << xs[i] << ") = " << ys[i] << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- An object with
operator()is called a functor (function object). Unlike a plain function, it can carry state, here the coefficients. - Horner’s method evaluates a polynomial of degree n with only n multiplications and n additions.
- Because
pis callable, it can be passed to any STL algorithm that expects a function, such asstd::transform.
Exercise 36: lvalue vs rvalue References
Practice Problem: Write two overloads of a function process(): one taking const std::string& (lvalue) and one taking std::string&& (rvalue). Call it with a named variable, a temporary, a string literal, and std::move(variable), and print which overload runs.
Expected Output:
lvalue overload: "Alice" (copy needed to keep it)
rvalue overload: "Temp" (safe to steal its data)
rvalue overload: "Hello from a function" (safe to steal its data)
rvalue overload: "Literal" (safe to steal its data)
rvalue overload: "Alice" (safe to steal its data)
lvalue overload: "Bound" (copy needed to keep it)
+ Hint
- An lvalue has a name and an address (a variable). An rvalue is a temporary that is about to disappear.
std::movedoes not move anything by itself. It is just a cast that turns an lvalue into an rvalue reference.
+ Show Solution
#include <iostream>
#include <string>
void process(const std::string& s) {
std::cout << "lvalue overload: \"" << s << "\" (copy needed to keep it)" << std::endl;
}
void process(std::string&& s) {
std::cout << "rvalue overload: \"" << s << "\" (safe to steal its data)" << std::endl;
}
std::string makeGreeting() { return "Hello from a function"; }
int main() {
std::string name = "Alice";
process(name); // named variable -> lvalue
process(std::string("Temp")); // temporary -> rvalue
process(makeGreeting()); // returned by value -> rvalue
process("Literal"); // converted to a temporary std::string -> rvalue
process(std::move(name)); // cast to rvalue
std::string&& ref = std::string("Bound");
process(ref); // a named rvalue reference is itself an lvalue!
return 0;
}Code language: C++ (cpp)
Explanation:
- The compiler selects the
&&overload for anything temporary, because nobody else can observe it afterwards. std::move(name)only casts. Sinceprocess()does not actually move froms,nameis unchanged here.- The last call is a common surprise: a variable declared as
std::string&&has a name, so using it is an lvalue expression and the lvalue overload is chosen.
Exercise 37: Move Constructor vs Copy Constructor
Practice Problem: Create a Buffer class that owns a heap array. Implement a copy constructor (deep copy) and a move constructor (steal the pointer). Print a message in each, and create buffers by copying and by moving to show which one runs.
Given:
Buffer a(1000);Code language: Python (python)
Expected Output:
Constructed buffer of 1000 ints
Copy constructor: allocated and copied 1000 ints
Move constructor: stole the pointer, no allocation
a size after move: 0
b size: 1000
c size: 1000
+ Hint
- The move constructor takes
Buffer&& other, copiesother.dataandother.size, then setsother.data = nullptrandother.size = 0. - Mark the move constructor
noexceptso standard containers will use it when they reallocate.
+ Show Solution
#include <algorithm>
#include <iostream>
class Buffer {
int* data;
size_t size;
public:
explicit Buffer(size_t n) : data(new int[n]), size(n) {
std::fill(data, data + size, 7);
std::cout << "Constructed buffer of " << size << " ints" << std::endl;
}
Buffer(const Buffer& other) : data(new int[other.size]), size(other.size) {
std::copy(other.data, other.data + size, data);
std::cout << "Copy constructor: allocated and copied " << size << " ints" << std::endl;
}
Buffer(Buffer&& other) noexcept : data(other.data), size(other.size) {
other.data = nullptr;
other.size = 0;
std::cout << "Move constructor: stole the pointer, no allocation" << std::endl;
}
Buffer& operator=(const Buffer&) = delete;
Buffer& operator=(Buffer&&) = delete;
~Buffer() { delete[] data; }
size_t getSize() const { return size; }
};
int main() {
Buffer a(1000);
Buffer b = a; // copy
Buffer c = std::move(a); // move
std::cout << "a size after move: " << a.getSize() << std::endl;
std::cout << "b size: " << b.getSize() << std::endl;
std::cout << "c size: " << c.getSize() << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The copy constructor allocates a new array and copies every element, which costs O(n).
- The move constructor just takes ownership of the existing pointer, which costs O(1) no matter how large the buffer is.
- The moved-from object
ais left in a valid empty state (nullptr, size 0), so its destructor can safely calldelete[]onnullptr.
Exercise 38: Rule of Five: A Complete Resource-Owning Class
Practice Problem: Implement a class MyString that owns a char* buffer and follows the Rule of Five: destructor, copy constructor, copy assignment, move constructor, and move assignment. Print a short tag from each special member and exercise all of them in main().
Expected Output:
[copy ctor] b = alpha
[move ctor] c = alpha, a = (empty)
[copy assign] d = alpha
[move assign] d = omega
[copy assign] self-assign kept d = omega
+ Hint
- If a class needs a custom destructor, it almost always needs custom copy and move operations too. That is the Rule of Five.
- In assignment operators, guard against self-assignment and release the old buffer before taking the new one.
- Use
std::strlenandstd::memcpyfrom<cstring>to manage the characters.
+ Show Solution
#include <cstring>
#include <iostream>
#include <utility>
class MyString {
char* buf;
size_t len;
void assign(const char* s, size_t n) {
buf = new char[n + 1];
std::memcpy(buf, s, n + 1);
len = n;
}
public:
MyString(const char* s = "") { assign(s, std::strlen(s)); }
~MyString() { delete[] buf; } // 1
MyString(const MyString& o) { // 2
assign(o.buf, o.len);
std::cout << "[copy ctor] ";
}
MyString& operator=(const MyString& o) { // 3
std::cout << "[copy assign] ";
if (this != &o) {
delete[] buf;
assign(o.buf, o.len);
}
return *this;
}
MyString(MyString&& o) noexcept : buf(o.buf), len(o.len) { // 4
o.buf = nullptr;
o.len = 0;
std::cout << "[move ctor] ";
}
MyString& operator=(MyString&& o) noexcept { // 5
std::cout << "[move assign] ";
if (this != &o) {
delete[] buf;
buf = o.buf;
len = o.len;
o.buf = nullptr;
o.len = 0;
}
return *this;
}
const char* c_str() const { return buf ? buf : "(empty)"; }
};
int main() {
MyString a("alpha");
MyString b = a; std::cout << "b = " << b.c_str() << std::endl;
MyString c = std::move(a); std::cout << "c = " << c.c_str() << ", a = " << a.c_str() << std::endl;
MyString d("delta");
d = b; std::cout << "d = " << d.c_str() << std::endl;
d = MyString("omega"); std::cout << "d = " << d.c_str() << std::endl;
MyString& alias = d;
d = alias; std::cout << "self-assign kept d = " << d.c_str() << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Copy operations make an independent deep copy, so changing one string never affects another.
- Move operations transfer the buffer and leave the source empty, which is why
aprints “(empty)” afterstd::move(a). d = MyString("omega")assigns from a temporary, so the move assignment operator is used automatically. Thethis != &ocheck makes self-assignment (d = alias, wherealiasrefers tod) harmless.
Exercise 39: Copies vs Moves When Filling a Vector
Practice Problem: Create a class Item whose copy and move constructors increment static counters. Insert objects into a std::vector<Item> using push_back(obj), push_back(std::move(obj)), and emplace_back(args), and print how many copies and moves each approach performs.
Expected Output:
push_back(a) -> copies: 1, moves: 0
push_back(std::move(b)) -> copies: 0, moves: 1
push_back(Item(...)) -> copies: 0, moves: 1
emplace_back("date") -> copies: 0, moves: 0
Vector holds: apple banana cherry date
+ Hint
- Call
reserve()first so the vector does not reallocate during the test. Reallocation would add extra moves and hide the result. emplace_backforwards its arguments to the constructor and builds the object directly inside the vector.
+ Show Solution
#include <iostream>
#include <string>
#include <vector>
struct Item {
std::string name;
inline static int copies = 0;
inline static int moves = 0;
explicit Item(std::string n) : name(std::move(n)) {}
Item(const Item& o) : name(o.name) { ++copies; }
Item(Item&& o) noexcept : name(std::move(o.name)) { ++moves; }
static void report(const std::string& label) {
std::cout << label << " -> copies: " << copies << ", moves: " << moves << std::endl;
copies = moves = 0;
}
};
int main() {
std::vector<Item> items;
items.reserve(10);
Item a("apple");
items.push_back(a);
Item::report("push_back(a) ");
Item b("banana");
items.push_back(std::move(b));
Item::report("push_back(std::move(b))");
items.push_back(Item("cherry"));
Item::report("push_back(Item(...)) ");
items.emplace_back("date");
Item::report("emplace_back(\"date\") ");
std::cout << "Vector holds: ";
for (const auto& it : items) std::cout << it.name << " ";
std::cout << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Pushing a named object (an lvalue) must copy it, because
ais still usable afterward. std::move(b)and a temporaryItem("cherry")both bind to the rvalue overload ofpush_back, so they are moved instead of copied.emplace_backconstructs the element in place, performing neither a copy nor a move. This is the most efficient choice when you have constructor arguments.
Exercise 40: Copy-and-Swap Idiom
Practice Problem: Rewrite the assignment operator of a resource-owning class IntArray using the copy-and-swap idiom: a single operator= that takes its parameter by value and swaps. Show that it handles copy assignment, move assignment, and self-assignment.
Given:
IntArray a(3, 1), b(5, 9);Code language: Python (python)
Expected Output:
a: [1, 1, 1] size=3
b: [9, 9, 9, 9, 9] size=5
a after a = b: [9, 9, 9, 9, 9] size=5
a after a = IntArray(2, 4): [4, 4] size=2
a after self-assignment: [4, 4] size=2
c after c = std::move(b): [9, 9, 9, 9, 9] size=5
b after move: [] size=0
+ Hint
- Write a
friend void swap(IntArray& a, IntArray& b) noexceptthat swaps the pointer and size withstd::swap. IntArray& operator=(IntArray other): the parameter is created by the copy or move constructor, thenswap(*this, other)takes its contents, andotherdestroys the old data when it goes out of scope.
+ Show Solution
#include <algorithm>
#include <iostream>
#include <utility>
class IntArray {
int* data;
size_t size;
public:
explicit IntArray(size_t n = 0, int fill = 0) : data(n ? new int[n] : nullptr), size(n) {
std::fill(data, data + size, fill);
}
IntArray(const IntArray& o) : IntArray(o.size) {
std::copy(o.data, o.data + size, data);
}
IntArray(IntArray&& o) noexcept : data(o.data), size(o.size) {
o.data = nullptr;
o.size = 0;
}
~IntArray() { delete[] data; }
friend void swap(IntArray& a, IntArray& b) noexcept {
std::swap(a.data, b.data);
std::swap(a.size, b.size);
}
IntArray& operator=(IntArray other) { // by value: copy OR move happens here
swap(*this, other);
return *this; // old data is freed when 'other' dies
}
void print(const char* label) const {
std::cout << label << ": [";
for (size_t i = 0; i < size; i++) std::cout << data[i] << (i + 1 < size ? ", " : "");
std::cout << "] size=" << size << std::endl;
}
};
int main() {
IntArray a(3, 1), b(5, 9);
a.print("a");
b.print("b");
a = b; // copy assignment
a.print("a after a = b");
a = IntArray(2, 4); // move assignment from a temporary
a.print("a after a = IntArray(2, 4)");
IntArray& same = a;
a = same; // self-assignment is safe
a.print("a after self-assignment");
IntArray c;
c = std::move(b);
c.print("c after c = std::move(b)");
b.print("b after move");
return 0;
}Code language: C++ (cpp)
Explanation:
- One
operator=covers both copy and move assignment, because the by-value parameter is built with whichever constructor matches the argument. - It gives the strong exception guarantee: if the copy throws, it throws before
*thisis touched, so the object keeps its old value. - Self-assignment works without a special check, because
ais swapped with a separate copy of itself.
Exercise 41: Erase Elements from a Vector While Iterating
Practice Problem: Given a std::vector<int>, remove all even numbers using iterators in a single loop. Then insert the value 100 at position 2 using insert().
Given:
std::vector<int> v = {3, 8, 5, 12, 7, 6, 9, 10};Code language: Python (python)
Expected Output:
Original: 3 8 5 12 7 6 9 10
Odds only: 3 5 7 9
After insert at index 2: 3 5 100 7 9
Size: 5, front: 3, back: 9
+ Hint
erase(it)invalidatesitbut returns an iterator to the next element. Useit = v.erase(it);and only incrementitwhen nothing was erased.v.insert(v.begin() + 2, 100)inserts before the element at index 2.
+ Show Solution
#include <iostream>
#include <vector>
void print(const std::vector<int>& v, const char* label) {
std::cout << label;
for (auto it = v.begin(); it != v.end(); ++it) std::cout << *it << " ";
std::cout << std::endl;
}
int main() {
std::vector<int> v = {3, 8, 5, 12, 7, 6, 9, 10};
print(v, "Original: ");
for (auto it = v.begin(); it != v.end(); ) {
if (*it % 2 == 0)
it = v.erase(it); // erase returns the next valid iterator
else
++it;
}
print(v, "Odds only: ");
v.insert(v.begin() + 2, 100);
print(v, "After insert at index 2: ");
std::cout << "Size: " << v.size() << ", front: " << v.front() << ", back: " << v.back() << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Calling
++itaftererase(it)would use an invalidated iterator, which is undefined behavior. Reassigningitfrom the return value avoids that. - Each
erase()in the middle of a vector shifts the following elements left, so this loop is O(n²) in the worst case. The erase-remove idiom in a later exercise does it in O(n). front()andback()give direct access to the first and last elements.
Exercise 42: Word Frequency Counter with std::map
Practice Problem: Count how many times each word appears in a sentence using std::map<std::string, int>. Convert words to lowercase and strip punctuation, then print the words in alphabetical order with their counts and report the most frequent word.
Given:
std::string text = "The cat and the hat. The cat sat on the mat, and the cat napped!";Code language: Python (python)
Expected Output:
and: 2
cat: 3
hat: 1
mat: 1
napped: 1
on: 1
sat: 1
the: 5
Most frequent: "the" (5 times)
+ Hint
- Read words with
std::istringstream. Clean each word by keeping only characters for whichstd::isalphais true, converted withstd::tolower. freq[word]++inserts the word with count 0 if it is new, then increments it.
+ Show Solution
#include <cctype>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
int main() {
std::string text = "The cat and the hat. The cat sat on the mat, and the cat napped!";
std::map<std::string, int> freq;
std::istringstream iss(text);
std::string raw;
while (iss >> raw) {
std::string word;
for (char ch : raw) {
if (std::isalpha(static_cast<unsigned char>(ch)))
word += static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
if (!word.empty()) freq[word]++;
}
std::string topWord;
int topCount = 0;
for (const auto& [word, count] : freq) {
std::cout << word << ": " << count << std::endl;
if (count > topCount) {
topCount = count;
topWord = word;
}
}
std::cout << "Most frequent: \"" << topWord << "\" (" << topCount << " times)" << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
std::mapkeeps its keys sorted, so iterating over it prints words alphabetically without any extra sorting.- Structured bindings
const auto& [word, count]unpack each key-value pair for readable code. - Casting to
unsigned charbefore callingstd::isalpha/std::toloweravoids undefined behavior for negativecharvalues.
Exercise 43: Remove Duplicates While Preserving Order
Practice Problem: Given a vector of integers, remove duplicate values but keep the first occurrence of each value in its original order. Use std::unordered_set to remember what has already been seen.
Given:
std::vector<int> nums = {4, 2, 4, 7, 2, 9, 7, 1, 4};Code language: Python (python)
Expected Output:
Original: 4 2 4 7 2 9 7 1 4
Unique: 4 2 7 9 1
Removed 4 duplicates
+ Hint
seen.insert(x)returns astd::pairwhose.secondistrueonly if the element was newly inserted.- Push an element into the result vector only when
insert(...).secondistrue.
+ Show Solution
#include <iostream>
#include <unordered_set>
#include <vector>
std::vector<int> uniqueInOrder(const std::vector<int>& input) {
std::unordered_set<int> seen;
std::vector<int> result;
for (int x : input) {
if (seen.insert(x).second) { // true when x was not seen before
result.push_back(x);
}
}
return result;
}
int main() {
std::vector<int> nums = {4, 2, 4, 7, 2, 9, 7, 1, 4};
std::vector<int> unique = uniqueInOrder(nums);
std::cout << "Original: ";
for (int x : nums) std::cout << x << " ";
std::cout << std::endl << "Unique: ";
for (int x : unique) std::cout << x << " ";
std::cout << std::endl;
std::cout << "Removed " << nums.size() - unique.size() << " duplicates" << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
std::unordered_setis a hash table, so each insert and lookup takes O(1) on average, giving O(n) for the whole function.- Using
insert().secondperforms the lookup and the insertion in one step instead of callingfind()and theninsert(). - A
std::setwould also work but would sort the values. Here the separate result vector keeps the original order.
Exercise 44: Balanced Brackets Using std::stack
Practice Problem: Write a function isBalanced() that uses std::stack<char> to check whether every (, [, and { in a string is closed in the correct order. Test it with several expressions.
Given:
"{[a + b] * (c - d)}", "((1 + 2) * 3", "[(])",
"if (x[0] == y) { run(); }", "}{"Code language: Python (python)
Expected Output:
Balanced: {[a + b] * (c - d)}
Not balanced: ((1 + 2) * 3
Not balanced: [(])
Balanced: if (x[0] == y) { run(); }
Not balanced: }{
+ Hint
- Push every opening bracket. For a closing bracket, the stack must be non-empty and its top must be the matching opening bracket. Pop it if so.
- At the end, the string is balanced only if the stack is empty.
+ Show Solution
#include <iostream>
#include <stack>
#include <string>
#include <vector>
bool isBalanced(const std::string& s) {
std::stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (st.empty()) return false;
char open = st.top();
if ((c == ')' && open != '(') ||
(c == ']' && open != '[') ||
(c == '}' && open != '{')) return false;
st.pop();
}
}
return st.empty();
}
int main() {
std::vector<std::string> tests = {
"{[a + b] * (c - d)}",
"((1 + 2) * 3",
"[(])",
"if (x[0] == y) { run(); }",
"}{"
};
for (const auto& t : tests) {
std::cout << (isBalanced(t) ? "Balanced: " : "Not balanced: ") << t << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- A stack is LIFO (last in, first out), which matches how brackets nest: the most recently opened bracket must close first.
[(])fails because]arrives while(is on top of the stack.- Characters that are not brackets are simply ignored, so the function works on real code or math expressions.
Exercise 45: Generate Binary Numbers Using std::queue
Practice Problem: Use a std::queue<std::string> to generate the binary representations of the numbers 1 to N (N = 10) without any arithmetic conversion.
Given:
int n = 10;Code language: Python (python)
Expected Output:
1 -> 1
2 -> 10
3 -> 11
4 -> 100
5 -> 101
6 -> 110
7 -> 111
8 -> 1000
9 -> 1001
10 -> 1010
Strings still waiting in queue: 11
+ Hint
- Start by pushing “1” into the queue.
- Repeat N times: take the front string, print it, pop it, and push the string with “0” appended and then with “1” appended.
+ Show Solution
#include <iostream>
#include <queue>
#include <string>
int main() {
int n = 10;
std::queue<std::string> q;
q.push("1");
for (int i = 1; i <= n; i++) {
std::string current = q.front();
q.pop();
std::cout << i << " -> " << current << std::endl;
q.push(current + "0");
q.push(current + "1");
}
std::cout << "Strings still waiting in queue: " << q.size() << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- A queue is FIFO (first in, first out), so the strings come out in breadth-first order, which is exactly increasing numeric order.
- Each string generates its two children, “x0” (2x) and “x1” (2x + 1), just like a binary tree.
- After printing N values, N + 1 strings remain in the queue: each of the N iterations removes one and adds two, starting from one.
Exercise 46: Task Scheduler with std::priority_queue
Practice Problem: Store tasks (name and priority) in a std::priority_queue with a custom comparator so that the task with the lowest priority number runs first. If two tasks have the same priority, the one added earlier runs first.
Given:
{"Write report", 3}, {"Fix prod bug", 1}, {"Reply emails", 4},
{"Code review", 2}, {"Deploy hotfix", 1}Code language: Python (python)
Expected Output:
Processing tasks:
[P1] Fix prod bug
[P1] Deploy hotfix
[P2] Code review
[P3] Write report
[P4] Reply emails
+ Hint
- By default
priority_queueis a max-heap. To get a min-heap by priority, the comparator must returntruewhen the first task should come after the second. - Give each task a sequence number to break ties in insertion order.
+ Show Solution
#include <iostream>
#include <queue>
#include <string>
#include <vector>
struct Task {
std::string name;
int priority; // 1 = most urgent
int order; // insertion order for ties
};
struct LaterFirst {
bool operator()(const Task& a, const Task& b) const {
if (a.priority != b.priority) return a.priority > b.priority;
return a.order > b.order;
}
};
int main() {
std::priority_queue<Task, std::vector<Task>, LaterFirst> pq;
int seq = 0;
pq.push({"Write report", 3, seq++});
pq.push({"Fix prod bug", 1, seq++});
pq.push({"Reply emails", 4, seq++});
pq.push({"Code review", 2, seq++});
pq.push({"Deploy hotfix", 1, seq++});
std::cout << "Processing tasks:" << std::endl;
while (!pq.empty()) {
const Task& t = pq.top();
std::cout << " [P" << t.priority << "] " << t.name << std::endl;
pq.pop();
}
return 0;
}Code language: C++ (cpp)
Explanation:
priority_queuekeeps the element that compares “largest” on top. Reversing the comparison (>) turns it into a min-heap.push()andpop()take O(log n), andtop()takes O(1).- Both priority-1 tasks run first, in the order they were added, thanks to the
ordertie-breaker.
Exercise 47: Group Anagrams Using a Map of Vectors
Practice Problem: Group a list of words into anagram groups using std::map<std::string, std::vector<std::string>>. Two words are anagrams if their sorted letters are identical.
Given:
std::vector<std::string> words = {"listen", "silent", "enlist", "google",
"gogole", "cat", "act", "tac", "dog"};Code language: Python (python)
Expected Output:
Found 4 groups:
act -> cat act tac
dgo -> dog
eggloo -> google gogole
eilnst -> listen silent enlist
+ Hint
- For each word, make a copy and sort its characters with
std::sort. Use the sorted string as the map key. groups[key].push_back(word)creates an empty vector the first time a key is seen.
+ Show Solution
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::vector<std::string> words = {"listen", "silent", "enlist", "google",
"gogole", "cat", "act", "tac", "dog"};
std::map<std::string, std::vector<std::string>> groups;
for (const auto& w : words) {
std::string key = w;
std::sort(key.begin(), key.end());
groups[key].push_back(w);
}
std::cout << "Found " << groups.size() << " groups:" << std::endl;
for (const auto& [key, list] : groups) {
std::cout << key << " -> ";
for (const auto& w : list) std::cout << w << " ";
std::cout << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Sorting the letters produces a canonical key: every anagram of “listen” becomes “eilnst”.
- A map can hold any copyable type as its value, including a whole
std::vector. - Because
std::mapis ordered, the groups are printed sorted by their key.
Exercise 48: Sliding Window Maximum with std::deque
Practice Problem: Given an array and a window size k = 3, print the maximum of every contiguous window in O(n) time using a std::deque<int> that stores indices.
Given:
std::vector<int> arr = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;Code language: Python (python)
Expected Output:
Window [1, 3, -1] max = 3
Window [3, -1, -3] max = 3
Window [-1, -3, 5] max = 5
Window [-3, 5, 3] max = 5
Window [5, 3, 6] max = 6
Window [3, 6, 7] max = 7
+ Hint
- Keep indices in the deque so their values are in decreasing order. Before pushing index i, pop from the back every index whose value is less than or equal to
arr[i]. - Pop from the front when the index falls out of the window (
dq.front() <= i - k). The front then always holds the index of the window maximum.
+ Show Solution
#include <deque>
#include <iostream>
#include <vector>
std::vector<int> windowMax(const std::vector<int>& arr, int k) {
std::deque<int> dq; // stores indices
std::vector<int> result;
for (int i = 0; i < static_cast<int>(arr.size()); i++) {
if (!dq.empty() && dq.front() <= i - k) dq.pop_front(); // out of window
while (!dq.empty() && arr[dq.back()] <= arr[i]) dq.pop_back(); // smaller values useless
dq.push_back(i);
if (i >= k - 1) result.push_back(arr[dq.front()]);
}
return result;
}
int main() {
std::vector<int> arr = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;
std::vector<int> maxes = windowMax(arr, k);
for (size_t i = 0; i < maxes.size(); i++) {
std::cout << "Window [";
for (size_t j = i; j < i + k; j++) std::cout << arr[j] << (j + 1 < i + k ? ", " : "");
std::cout << "] max = " << maxes[i] << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
std::dequesupports fast insertion and removal at both ends, which this algorithm needs.- Each index is pushed once and popped at most once, so the total work is O(n) even though there is a loop inside a loop.
- A smaller element that arrives before a larger one can never be a window maximum again, so it is removed from the back immediately.
Exercise 49: Sort Structs by Multiple Criteria with a Lambda
Practice Problem: Given a list of students, sort them by marks in descending order, and alphabetically by name when marks are equal, using std::sort with a lambda comparator.
Given:
{"Ravi", 82}, {"Anita", 95}, {"John", 82},
{"Meera", 76}, {"Carl", 95}, {"Zoya", 88}Code language: Python (python)
Expected Output:
1. Anita - 95
2. Carl - 95
3. Zoya - 88
4. John - 82
5. Ravi - 82
6. Meera - 76
+ Hint
- The comparator returns
truewhenashould come beforeb. - Compare marks first. Only when they are equal, compare names with
a.name < b.name.
+ Show Solution
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
struct Student {
std::string name;
int marks;
};
int main() {
std::vector<Student> students = {
{"Ravi", 82}, {"Anita", 95}, {"John", 82},
{"Meera", 76}, {"Carl", 95}, {"Zoya", 88}
};
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
if (a.marks != b.marks) return a.marks > b.marks; // higher marks first
return a.name < b.name; // then by name
});
int rank = 1;
for (const auto& s : students) {
std::cout << rank++ << ". " << s.name << " - " << s.marks << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- A lambda lets you write the comparison right where it is used, instead of a separate function or functor class.
- Students with equal marks (Anita/Carl and John/Ravi) are ordered by name because of the second comparison.
- The comparator must define a strict weak ordering: never return
truefor equal elements, which is why>and<are used instead of>=or<=.
Exercise 50: count_if, find_if, all_of, any_of
Practice Problem: Given a list of product prices, use STL algorithms with lambdas to: count prices above a threshold, find the first price below 10, and check whether all prices are positive and whether any price exceeds 500.
Given:
std::vector<double> prices = {49.99, 15.5, 120.0, 8.75, 299.0, 5.25, 75.0};
double threshold = 50.0;Code language: Python (python)
Expected Output:
Prices above 50: 3
First price under 10: 8.75 at index 3
All prices positive? true
Any price above 500? false
+ Hint
std::count_if(begin, end, pred)returns how many elements satisfypred.std::find_ifreturns an iterator to the first matching element, orend()if none match. Usestd::distanceto turn it into an index.- A lambda can capture a local variable such as
thresholdwith[threshold].
+ Show Solution
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::vector<double> prices = {49.99, 15.5, 120.0, 8.75, 299.0, 5.25, 75.0};
double threshold = 50.0;
auto expensive = std::count_if(prices.begin(), prices.end(),
[threshold](double p) { return p > threshold; });
std::cout << "Prices above " << threshold << ": " << expensive << std::endl;
auto it = std::find_if(prices.begin(), prices.end(), [](double p) { return p < 10; });
if (it != prices.end()) {
std::cout << "First price under 10: " << *it
<< " at index " << std::distance(prices.begin(), it) << std::endl;
}
bool allPositive = std::all_of(prices.begin(), prices.end(), [](double p) { return p > 0; });
bool anyHuge = std::any_of(prices.begin(), prices.end(), [](double p) { return p > 500; });
std::cout << std::boolalpha;
std::cout << "All prices positive? " << allPositive << std::endl;
std::cout << "Any price above 500? " << anyHuge << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- These algorithms replace hand-written loops with names that state the intent clearly.
[threshold]captures the variable by value, so the lambda keeps its own copy.all_ofandany_ofstop early as soon as the answer is known, so they do not always visit every element.
Exercise 51: transform and accumulate
Practice Problem: Use std::transform to create a vector of squares from a list of numbers, then use std::accumulate to compute the sum of squares, the product of the original numbers, and a comma-separated string of the numbers.
Given:
std::vector<int> nums = {2, 3, 5, 7, 11};Code language: Python (python)
Expected Output:
Squares: 4 9 25 49 121
Sum of squares: 208
Product: 2310
As text: 2, 3, 5, 7, 11
+ Hint
std::accumulateis in<numeric>. Its third argument is the initial value, and its type decides the result type (use1LLfor along longproduct).- Pass a lambda as the fourth argument to
accumulateto use an operation other than+.
+ Show Solution
#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
int main() {
std::vector<int> nums = {2, 3, 5, 7, 11};
std::vector<int> squares(nums.size());
std::transform(nums.begin(), nums.end(), squares.begin(), [](int x) { return x * x; });
int sumSquares = std::accumulate(squares.begin(), squares.end(), 0);
long long product = std::accumulate(nums.begin(), nums.end(), 1LL,
[](long long acc, int x) { return acc * x; });
std::string csv = std::accumulate(std::next(nums.begin()), nums.end(),
std::to_string(nums[0]),
[](std::string acc, int x) { return acc + ", " + std::to_string(x); });
std::cout << "Squares: ";
for (int s : squares) std::cout << s << " ";
std::cout << std::endl;
std::cout << "Sum of squares: " << sumSquares << std::endl;
std::cout << "Product: " << product << std::endl;
std::cout << "As text: " << csv << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
std::transformapplies the lambda to every element and writes the results to the output range, which must already be large enough.accumulateis a general fold: it works for sums, products, and even building strings.- The CSV string starts from the first number and folds the rest with
", "in between, so there is no trailing comma.
Exercise 52: Lambda Captures: By Value, By Reference, and mutable
Practice Problem: Write a program that demonstrates the difference between capturing a variable by value [x], by reference [&x], and a mutable lambda that keeps its own internal counter.
Given:
int x = 10;
int start = 100;
int a = 1, b = 2;Code language: Python (python)
Expected Output:
byValue sees: 10
byRef sees: 50
x after increment through reference: 55
counter: 100 101 102
start is still: 100
a = 1, b = 3
+ Hint
- A by-value capture copies the variable when the lambda is created, so later changes to the original are not seen.
- By default the copied variables are read-only inside the lambda. Adding
mutableallows the lambda to modify its own copy.
+ Show Solution
#include <iostream>
int main() {
int x = 10;
auto byValue = [x]() { return x; };
auto byRef = [&x]() { return x; };
x = 50; // change after the lambdas were created
std::cout << "byValue sees: " << byValue() << std::endl;
std::cout << "byRef sees: " << byRef() << std::endl;
auto increment = [&x]() { x += 5; };
increment();
std::cout << "x after increment through reference: " << x << std::endl;
int start = 100;
auto counter = [start]() mutable { return start++; };
std::cout << "counter: " << counter() << " " << counter() << " " << counter() << std::endl;
std::cout << "start is still: " << start << std::endl;
int a = 1, b = 2;
auto mixed = [=, &b]() { b = a + b; }; // everything by value except b
mixed();
std::cout << "a = " << a << ", b = " << b << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
byValuestored a copy ofxwhen it was 10, so it still returns 10.byRefreads the current value, 50.- The
mutablecounter changes its private copy ofstart. The originalstartinmain()remains 100. [=, &b]captures everything by value by default butbby reference. Be careful with reference captures if the lambda outlives the variables.
Exercise 53: Erase-Remove Idiom and partition
Practice Problem: Given a vector of integers, remove all negative numbers using the erase-remove idiom with std::remove_if. Then use std::partition to move all even numbers before the odd numbers.
Given:
std::vector<int> v = {5, -3, 8, -1, 12, 7, -9, 4, 3, 10};Code language: Python (python)
Expected Output:
Original: 5 -3 8 -1 12 7 -9 4 3 10
Without negatives: 5 8 12 7 4 3 10
Evens first: 8 12 4 10 5 7 3
Number of evens: 4
First odd value: 5
+ Hint
std::remove_ifdoes not shrink the container. It moves the kept elements to the front and returns an iterator to the new logical end. Pass that iterator toerase().std::partitionreturns an iterator to the first element of the second group. Usestd::stable_partitionif you need to keep the relative order.
+ Show Solution
#include <algorithm>
#include <iostream>
#include <vector>
void print(const std::vector<int>& v, const char* label) {
std::cout << label;
for (int x : v) std::cout << x << " ";
std::cout << std::endl;
}
int main() {
std::vector<int> v = {5, -3, 8, -1, 12, 7, -9, 4, 3, 10};
print(v, "Original: ");
v.erase(std::remove_if(v.begin(), v.end(), [](int x) { return x < 0; }), v.end());
print(v, "Without negatives: ");
auto mid = std::stable_partition(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
print(v, "Evens first: ");
std::cout << "Number of evens: " << (mid - v.begin()) << std::endl;
std::cout << "First odd value: " << *mid << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The erase-remove idiom runs in O(n), because each kept element is moved at most once.
stable_partitionkeeps the original relative order inside each group, so the output is predictable: 8 12 4 10, then 5 7 3.- The returned iterator
midmarks the boundary between the two groups, so the number of evens ismid - v.begin().
Exercise 54: Calculator Using std::function and a Map of Lambdas
Practice Problem: Build a small calculator that maps operator symbols to lambdas using std::map<char, std::function<double(double, double)>>. Evaluate a list of expressions and report unknown operators.
Given:
{6, '+', 4}, {9, '-', 12}, {2.5, '*', 4},
{7, '/', 2}, {2, '^', 10}, {5, '%', 3}Code language: Python (python)
Expected Output:
6 + 4 = 10
9 - 12 = -3
2.5 * 4 = 10
7 / 2 = 3.5
2 ^ 10 = 1024
5 % 3 = unknown operator
+ Hint
std::function<double(double, double)>can store any callable with that signature: lambdas, free functions, or functors.- Use
ops.find(op)to check whether an operator exists before calling it.
+ Show Solution
#include <cmath>
#include <functional>
#include <iostream>
#include <map>
#include <vector>
struct Expr { double a; char op; double b; };
int main() {
std::map<char, std::function<double(double, double)>> ops = {
{'+', [](double a, double b) { return a + b; }},
{'-', [](double a, double b) { return a - b; }},
{'*', [](double a, double b) { return a * b; }},
{'/', [](double a, double b) { return a / b; }},
{'^', [](double a, double b) { return std::pow(a, b); }}
};
std::vector<Expr> exprs = {{6, '+', 4}, {9, '-', 12}, {2.5, '*', 4},
{7, '/', 2}, {2, '^', 10}, {5, '%', 3}};
for (const auto& e : exprs) {
auto it = ops.find(e.op);
if (it == ops.end()) {
std::cout << e.a << " " << e.op << " " << e.b << " = unknown operator" << std::endl;
} else {
std::cout << e.a << " " << e.op << " " << e.b << " = " << it->second(e.a, e.b) << std::endl;
}
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Every lambda has its own unique type, so
std::functionis needed to store different lambdas in the same container. - Adding a new operator only requires one more entry in the map. No
switchstatement has to change. it->second(e.a, e.b)calls the stored function object just like a normal function.
Exercise 55: Binary Search with lower_bound and upper_bound
Practice Problem: Sort a vector of exam scores, then use std::binary_search, std::lower_bound, std::upper_bound, and std::equal_range to answer: does 75 exist, how many students scored exactly 75, and how many scored at least 80?
Given:
std::vector<int> scores = {88, 75, 92, 60, 75, 81, 75, 99, 70, 80};Code language: Python (python)
Expected Output:
Sorted: 60 70 75 75 75 80 81 88 92 99
Contains 75? true
Contains 85? false
Count of 75: 3 (indices 2 to 4)
Scores >= 80: 5
Scores <= 70: 2
+ Hint
- All these functions require the range to be sorted first.
lower_boundreturns the first element not less than the value.upper_boundreturns the first element greater than the value. The distance between them is the count of that value.
+ Show Solution
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> scores = {88, 75, 92, 60, 75, 81, 75, 99, 70, 80};
std::sort(scores.begin(), scores.end());
std::cout << "Sorted: ";
for (int s : scores) std::cout << s << " ";
std::cout << std::endl;
std::cout << std::boolalpha;
std::cout << "Contains 75? " << std::binary_search(scores.begin(), scores.end(), 75) << std::endl;
std::cout << "Contains 85? " << std::binary_search(scores.begin(), scores.end(), 85) << std::endl;
auto [first, last] = std::equal_range(scores.begin(), scores.end(), 75);
std::cout << "Count of 75: " << (last - first)
<< " (indices " << (first - scores.begin()) << " to " << (last - scores.begin() - 1) << ")" << std::endl;
auto lb = std::lower_bound(scores.begin(), scores.end(), 80);
std::cout << "Scores >= 80: " << (scores.end() - lb) << std::endl;
auto ub = std::upper_bound(scores.begin(), scores.end(), 70);
std::cout << "Scores <= 70: " << (ub - scores.begin()) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Each search takes O(log n) on a sorted vector, compared to O(n) for a linear scan.
equal_rangereturns bothlower_boundandupper_boundas a pair, which unpacks neatly with structured bindings.- Because vector iterators are random-access, subtracting them gives the number of elements between them directly.
Exercise 56: Permutations with next_permutation
Practice Problem: Print all permutations of the string "ABC" in lexicographic order using std::next_permutation, and count them. Then print all distinct permutations of "AAB".
Given:
"ABC" and "AAB"Code language: Python (python)
Expected Output:
Permutations of ABC: ABC ACB BAC BCA CAB CBA
Total: 6
Permutations of AAB: AAB ABA BAA
Total (duplicates skipped): 3
+ Hint
- Sort the string first so you start from the smallest permutation.
std::next_permutationrearranges the range into the next greater permutation and returnsfalseonce it wraps around to the smallest one. Use it in ado ... whileloop.
+ Show Solution
#include <algorithm>
#include <iostream>
#include <string>
int printPermutations(std::string s) {
std::sort(s.begin(), s.end());
int count = 0;
do {
std::cout << s << " ";
count++;
} while (std::next_permutation(s.begin(), s.end()));
std::cout << std::endl;
return count;
}
int main() {
std::cout << "Permutations of ABC: ";
int c1 = printPermutations("ABC");
std::cout << "Total: " << c1 << std::endl;
std::cout << "Permutations of AAB: ";
int c2 = printPermutations("AAB");
std::cout << "Total (duplicates skipped): " << c2 << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The
do ... whileform prints the starting (sorted) arrangement before asking for the next one. next_permutationautomatically skips repeated arrangements, so “AAB” produces 3 permutations instead of 3! = 6.- The string is passed by value, so the caller’s original string is never modified.
Exercise 57: Generic findMax Function Template
Practice Problem: Write a function template findMax() that returns the largest element of a std::vector<T>. Test it with int, double, and std::string, and also write a template maxOf(a, b) for two values.
Given:
std::vector<int> ints = {14, 3, 27, 9};
std::vector<double> doubles = {2.5, 9.75, 1.25};
std::vector<std::string> names = {"pear", "apple", "zucchini", "mango"};Code language: Python (python)
Expected Output:
Max int: 27
Max double: 9.75
Max string: zucchini
maxOf(4, 11): 11
maxOf<double>(3, 2.5): 3
+ Hint
- Declare the template with
template <typename T>. The compiler deducesTfrom the argument type. - The type
Tonly needs to support<for these functions to work.
+ Show Solution
#include <iostream>
#include <string>
#include <vector>
template <typename T>
T findMax(const std::vector<T>& items) {
T best = items[0];
for (const T& item : items) {
if (best < item) best = item;
}
return best;
}
template <typename T>
const T& maxOf(const T& a, const T& b) {
return (a < b) ? b : a;
}
int main() {
std::vector<int> ints = {14, 3, 27, 9};
std::vector<double> doubles = {2.5, 9.75, 1.25};
std::vector<std::string> names = {"pear", "apple", "zucchini", "mango"};
std::cout << "Max int: " << findMax(ints) << std::endl;
std::cout << "Max double: " << findMax(doubles) << std::endl;
std::cout << "Max string: " << findMax(names) << std::endl;
std::cout << "maxOf(4, 11): " << maxOf(4, 11) << std::endl;
std::cout << "maxOf<double>(3, 2.5): " << maxOf<double>(3, 2.5) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- The compiler generates a separate version of
findMaxfor each type used:findMax<int>,findMax<double>, andfindMax<std::string>. - Strings compare lexicographically, so “zucchini” is the largest.
maxOf(3, 2.5)alone would fail becauseTcannot be bothintanddouble. WritingmaxOf<double>specifies the type explicitly.
Exercise 58: Template with a Non-Type Parameter
Practice Problem: Write a function template printArray() that accepts a built-in array of any type and any size by reference, and deduces the size automatically. Also write arraySum() that returns the sum.
Given:
int primes[] = {2, 3, 5, 7, 11, 13};
double temps[] = {21.5, 19.0, 23.25};
std::string parts[] = {"C", "+", "+"};Code language: Python (python)
Expected Output:
[6 items] 2, 3, 5, 7, 11, 13
[3 items] 21.5, 19, 23.25
[3 items] C, +, +
Sum of primes: 41
Sum of temps: 63.75
Joined parts: C++
+ Hint
- Use two template parameters: a type and a size,
template <typename T, std::size_t N>. - Declare the parameter as a reference to an array:
const T (&arr)[N]. This prevents the array from decaying to a pointer, soNcan be deduced.
+ Show Solution
#include <cstddef>
#include <iostream>
#include <string>
template <typename T, std::size_t N>
void printArray(const T (&arr)[N]) {
std::cout << "[" << N << " items] ";
for (std::size_t i = 0; i < N; i++) std::cout << arr[i] << (i + 1 < N ? ", " : "");
std::cout << std::endl;
}
template <typename T, std::size_t N>
T arraySum(const T (&arr)[N]) {
T total{};
for (const T& x : arr) total += x;
return total;
}
int main() {
int primes[] = {2, 3, 5, 7, 11, 13};
double temps[] = {21.5, 19.0, 23.25};
std::string parts[] = {"C", "+", "+"};
printArray(primes);
printArray(temps);
printArray(parts);
std::cout << "Sum of primes: " << arraySum(primes) << std::endl;
std::cout << "Sum of temps: " << arraySum(temps) << std::endl;
std::cout << "Joined parts: " << arraySum(parts) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
Nis a non-type template parameter: a compile-time constant value instead of a type.- Passing a normal
T* arrwould lose the size information. The reference-to-array parameter keeps it. T total{}value-initializes the accumulator: 0 for numbers and an empty string forstd::string, so the same code works for all three arrays.
Exercise 59: Generic Stack Class Template
Practice Problem: Write a class template Stack<T> backed by a std::vector<T> with push(), pop(), top(), size(), and empty(). Throw an exception when popping or reading from an empty stack. Use it with int and std::string.
Expected Output:
Int stack size: 4, top: 16
Going back: cart products home
Error: pop() on empty stack
+ Hint
- Write
template <typename T> class Stack { ... };and create objects withStack<int>andStack<std::string>. - Throw
std::underflow_error(from<stdexcept>) when the stack is empty.
+ Show Solution
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
template <typename T>
class Stack {
std::vector<T> items;
public:
void push(const T& value) { items.push_back(value); }
void pop() {
if (items.empty()) throw std::underflow_error("pop() on empty stack");
items.pop_back();
}
const T& top() const {
if (items.empty()) throw std::underflow_error("top() on empty stack");
return items.back();
}
std::size_t size() const { return items.size(); }
bool empty() const { return items.empty(); }
};
int main() {
Stack<int> numbers;
for (int i = 1; i <= 4; i++) numbers.push(i * i);
std::cout << "Int stack size: " << numbers.size() << ", top: " << numbers.top() << std::endl;
Stack<std::string> history;
history.push("home");
history.push("products");
history.push("cart");
std::cout << "Going back: ";
while (!history.empty()) {
std::cout << history.top() << " ";
history.pop();
}
std::cout << std::endl;
try {
history.pop();
} catch (const std::underflow_error& e) {
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- The class is written once, and the compiler creates
Stack<int>andStack<std::string>as separate classes. - Template member functions are defined inside the class (or in the header), because the compiler needs the full definition when it instantiates the template.
top()returnsconst T&to avoid copying potentially large objects.
Exercise 60: Class Template Specialization
Practice Problem: Create a class template TypeInfo<T> with a static function describe() that returns “generic type”. Provide full specializations for int, bool, and std::string, and a partial specialization for any pointer type T*.
Expected Output:
int (whole number)
bool (true/false)
std::string (text)
generic type
pointer to int (whole number)
pointer to pointer to int (whole number)
+ Hint
- A full specialization is written as
template <> struct TypeInfo<int> { ... };. - A partial specialization keeps a template parameter:
template <typename T> struct TypeInfo<T*> { ... };. It can use the primary template for the pointed-to type.
+ Show Solution
#include <iostream>
#include <string>
template <typename T>
struct TypeInfo {
static std::string describe() { return "generic type"; }
};
template <>
struct TypeInfo<int> {
static std::string describe() { return "int (whole number)"; }
};
template <>
struct TypeInfo<bool> {
static std::string describe() { return "bool (true/false)"; }
};
template <>
struct TypeInfo<std::string> {
static std::string describe() { return "std::string (text)"; }
};
template <typename T>
struct TypeInfo<T*> {
static std::string describe() { return "pointer to " + TypeInfo<T>::describe(); }
};
template <typename T>
void show(const T&) {
std::cout << TypeInfo<T>::describe() << std::endl;
}
int main() {
int n = 5;
show(n);
show(true);
show(std::string("hi"));
show(3.14);
show(&n);
int* p = &n;
show(&p); // int** -> pointer to pointer to int
return 0;
}Code language: C++ (cpp)
Explanation:
- The compiler always chooses the most specialized matching version, so
intuses its own specialization whiledoublefalls back to the generic one. - The pointer partial specialization is recursive: for
int**, it callsTypeInfo<int*>, which callsTypeInfo<int>. - Specialization is how the standard library customizes behavior for particular types, for example
std::hash<T>andstd::vector<bool>.
Exercise 61: Variadic Templates and Fold Expressions
Practice Problem: Write variadic function templates: sumAll(args...) that adds any number of values, printAll(args...) that prints values of different types separated by spaces, and countArgs(args...) that returns how many arguments were passed. Use C++17 fold expressions.
Expected Output:
sumAll(1, 2, 3, 4, 5) = 15
sumAll(1.5, 2, 3.25) = 6.75
sumAll(strings) = Hello, World
Mixed: 42 3.5 c text 1
countArgs(1, 'a', "b", 2.0) = 4
allEqual(7, 7, 7) = true
allEqual(7, 7, 8) = false
+ Hint
- Declare a parameter pack with
template <typename... Args>andArgs... args. - A fold expression such as
(args + ...)expands toa1 + (a2 + (a3 + ...)). Usesizeof...(args)to count the arguments.
+ Show Solution
#include <iostream>
#include <string>
template <typename... Args>
auto sumAll(Args... args) {
return (args + ...); // unary right fold
}
template <typename... Args>
void printAll(const Args&... args) {
((std::cout << args << ' '), ...); // comma fold
std::cout << std::endl;
}
template <typename... Args>
constexpr std::size_t countArgs(const Args&...) {
return sizeof...(Args);
}
template <typename T, typename... Args>
bool allEqual(const T& first, const Args&... rest) {
return ((first == rest) && ...);
}
int main() {
std::cout << "sumAll(1, 2, 3, 4, 5) = " << sumAll(1, 2, 3, 4, 5) << std::endl;
std::cout << "sumAll(1.5, 2, 3.25) = " << sumAll(1.5, 2, 3.25) << std::endl;
std::cout << "sumAll(strings) = " << sumAll(std::string("Hello"), std::string(", "), std::string("World")) << std::endl;
printAll("Mixed:", 42, 3.5, 'c', std::string("text"), true);
std::cout << "countArgs(1, 'a', \"b\", 2.0) = " << countArgs(1, 'a', "b", 2.0) << std::endl;
std::cout << std::boolalpha;
std::cout << "allEqual(7, 7, 7) = " << allEqual(7, 7, 7) << std::endl;
std::cout << "allEqual(7, 7, 8) = " << allEqual(7, 7, 8) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Variadic templates accept any number of arguments of any types, which is how functions such as
std::make_uniqueandstd::printf-style loggers are built. - Fold expressions (C++17) replace the older recursive approach with a single line.
- The comma fold
((std::cout << args << ' '), ...)runs the print expression once for every argument, from left to right.
Exercise 62: Constraining Templates with Type Traits and if constexpr
Practice Problem: Write a function template average() that only accepts arithmetic element types (enforced with static_assert and std::is_arithmetic_v). Also write describe(value) that uses if constexpr to print a different message for integers, floating-point numbers, strings, and other types.
Given:
std::vector<int> a = {4, 8, 15, 16, 23, 42};
std::vector<double> b = {1.5, 2.5, 4.0};Code language: Python (python)
Expected Output:
average(ints) = 18
average(doubles) = 2.66667
17 is an integer, odd
2.71828 is floating point, rounded: 3
"templates" is a string of length 9
some other type
+ Hint
- Type traits live in
<type_traits>.std::is_integral_v<T>andstd::is_floating_point_v<T>are compile-time booleans. if constexprdiscards the branches that do not apply at compile time, so code that would not compile for a type is never instantiated.
+ Show Solution
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>
template <typename T>
double average(const std::vector<T>& values) {
static_assert(std::is_arithmetic_v<T>, "average() requires a numeric type");
double sum = 0;
for (const T& v : values) sum += v;
return values.empty() ? 0.0 : sum / values.size();
}
template <typename T>
void describe(const T& value) {
if constexpr (std::is_integral_v<T>) {
std::cout << value << " is an integer, " << (value % 2 == 0 ? "even" : "odd") << std::endl;
} else if constexpr (std::is_floating_point_v<T>) {
std::cout << value << " is floating point, rounded: " << static_cast<long>(value + 0.5) << std::endl;
} else if constexpr (std::is_same_v<T, std::string>) {
std::cout << "\"" << value << "\" is a string of length " << value.size() << std::endl;
} else {
std::cout << "some other type" << std::endl;
}
}
int main() {
std::vector<int> a = {4, 8, 15, 16, 23, 42};
std::vector<double> b = {1.5, 2.5, 4.0};
std::cout << "average(ints) = " << average(a) << std::endl;
std::cout << "average(doubles) = " << average(b) << std::endl;
// average(std::vector<std::string>{"x"}); // compile error: requires a numeric type
describe(17);
describe(2.71828);
describe(std::string("templates"));
describe(a);
return 0;
}Code language: C++ (cpp)
Explanation:
static_assertproduces a clear compile-time error message instead of a long template error if someone callsaverage()with strings.- With a normal
if, the linevalue % 2would fail to compile fordoubleandstd::string.if constexprremoves that branch for those types. - In C++20 the same constraints can be written with concepts, but type traits plus
if constexprwork in C++17.
Exercise 63: Throw and Catch a runtime_error
Practice Problem: Write a function safeDivide(a, b) that throws std::runtime_error when b is zero. Call it in a loop over several pairs of numbers, catching the error so the program continues with the next pair.
Given:
{{10, 2}, {7, 0}, {9, 3}, {1, 0}, {5, 4}}Code language: Python (python)
Expected Output:
10 / 2 = 5
7 / 0 -> Error: Division by zero attempted
9 / 3 = 3
1 / 0 -> Error: Division by zero attempted
5 / 4 = 1.25
Completed with 2 failed divisions
+ Hint
- Use
throw std::runtime_error("message");inside the function. - Catch by const reference:
catch (const std::runtime_error& e), and printe.what().
+ Show Solution
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>
double safeDivide(double a, double b) {
if (b == 0) {
throw std::runtime_error("Division by zero attempted");
}
return a / b;
}
int main() {
std::vector<std::pair<double, double>> pairs = {{10, 2}, {7, 0}, {9, 3}, {1, 0}, {5, 4}};
int failures = 0;
for (const auto& [a, b] : pairs) {
try {
double result = safeDivide(a, b);
std::cout << a << " / " << b << " = " << result << std::endl;
} catch (const std::runtime_error& e) {
std::cout << a << " / " << b << " -> Error: " << e.what() << std::endl;
failures++;
}
}
std::cout << "Completed with " << failures << " failed divisions" << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- When
throwexecutes, the function stops immediately and control jumps to the nearest matchingcatchblock. - Because the
tryblock is inside the loop, one failure does not stop the remaining calculations. - Catching by
constreference avoids copying the exception and preserves its real (derived) type.
Exercise 64: Custom Exception Class
Practice Problem: Create a custom exception InsufficientFundsError derived from std::runtime_error that also stores the requested amount and the available balance. Throw it from Wallet::spend() and catch it in main() to print a detailed message.
Given:
Wallet w(100);
double purchases[] = {30, 45, 50, 20};Code language: Python (python)
Expected Output:
Spent 30, remaining 70
Spent 45, remaining 25
Insufficient funds: tried to spend 50, short by 25
Spent 20, remaining 5
+ Hint
- Derive from a standard exception and pass a message to the base constructor:
InsufficientFundsError(...) : std::runtime_error(msg), .... - Add getter methods for the extra data so the handler can use them.
+ Show Solution
#include <iostream>
#include <stdexcept>
#include <string>
class InsufficientFundsError : public std::runtime_error {
double requested, available;
public:
InsufficientFundsError(double req, double avail)
: std::runtime_error("Insufficient funds"), requested(req), available(avail) {}
double getRequested() const { return requested; }
double getShortfall() const { return requested - available; }
};
class Wallet {
double balance;
public:
explicit Wallet(double b) : balance(b) {}
void spend(double amount) {
if (amount > balance) throw InsufficientFundsError(amount, balance);
balance -= amount;
std::cout << "Spent " << amount << ", remaining " << balance << std::endl;
}
};
int main() {
Wallet w(100);
double purchases[] = {30, 45, 50, 20};
for (double p : purchases) {
try {
w.spend(p);
} catch (const InsufficientFundsError& e) {
std::cout << e.what() << ": tried to spend " << e.getRequested()
<< ", short by " << e.getShortfall() << std::endl;
}
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Deriving from
std::runtime_errormeans the custom exception can still be caught by any handler forstd::runtime_errororstd::exception. - Extra members such as
requestedandavailablegive the handler structured data instead of only a text message. - The failed purchase of 50 does not change the balance, so the later purchase of 20 still succeeds.
Exercise 65: Multiple catch Blocks and Catch Order
Practice Problem: Write a function that, based on a command string, can trigger different exceptions: std::out_of_range (from vector::at), std::invalid_argument (from std::stoi), a custom thrown int, or no error. Handle each with its own catch block, ordered from most specific to most general, ending with catch (...).
Given:
Commands: "ok", "index", "parse", "logic", "code"Code language: Python (python)
Expected Output:
Command 'ok' ran fine
out_of_range caught for 'index'
invalid_argument caught for 'parse'
Other std::exception: bad program state
Unknown exception caught for 'code'
+ Hint
- Place handlers for derived classes before handlers for their base classes.
catch (const std::exception&)would otherwise catch everything first. catch (...)catches anything, including non-class types such asint.
+ Show Solution
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
void run(const std::string& command) {
std::vector<int> data = {1, 2, 3};
if (command == "index") {
std::cout << data.at(10) << std::endl; // throws std::out_of_range
} else if (command == "parse") {
std::cout << std::stoi("abc") << std::endl; // throws std::invalid_argument
} else if (command == "code") {
throw 404; // throws an int
} else if (command == "logic") {
throw std::logic_error("bad program state");
}
std::cout << "Command '" << command << "' ran fine" << std::endl;
}
int main() {
for (const std::string cmd : {"ok", "index", "parse", "logic", "code"}) {
try {
run(cmd);
} catch (const std::out_of_range&) {
std::cout << "out_of_range caught for '" << cmd << "'" << std::endl;
} catch (const std::invalid_argument&) {
std::cout << "invalid_argument caught for '" << cmd << "'" << std::endl;
} catch (const std::exception& e) {
std::cout << "Other std::exception: " << e.what() << std::endl;
} catch (...) {
std::cout << "Unknown exception caught for '" << cmd << "'" << std::endl;
}
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Handlers are tried top to bottom, and the first matching one wins, so the order matters.
std::logic_errorhas no dedicated handler, so it is caught by the generalstd::exceptionblock.- Throwing an
intworks but is poor style. It can only be caught bycatch (int)orcatch (...)and carries no message. - The text returned by
what()for library exceptions (such as the one fromstd::stoi) differs between compilers, so the handlers above print their own messages.
Exercise 66: Stack Unwinding and Rethrowing
Practice Problem: Create a chain of function calls main → loadConfig → parseLine. Throw an exception deep in parseLine, catch it in loadConfig to log it, then rethrow it with throw; so main can handle it. Use an RAII object in each function to show that destructors run during stack unwinding.
Given:
parseLine("port=8080"), parseLine("timeout 30"), parseLine("debug=true")Code language: Python (python)
Expected Output:
enter loadConfig
enter parseLine
parsed: port=8080
cleanup parseLine
enter parseLine
cleanup parseLine
loadConfig logged: missing '=' in line: timeout 30
cleanup loadConfig
main handled invalid_argument: missing '=' in line: timeout 30
Program continues normally
+ Hint
- A bare
throw;inside acatchblock rethrows the same exception object, preserving its original type. - Create a small
Guardclass that prints a message in its destructor and declare one at the top of each function.
+ Show Solution
#include <iostream>
#include <stdexcept>
#include <string>
struct Guard {
std::string name;
explicit Guard(std::string n) : name(std::move(n)) { std::cout << " enter " << name << std::endl; }
~Guard() { std::cout << " cleanup " << name << std::endl; }
};
void parseLine(const std::string& line) {
Guard g("parseLine");
if (line.find('=') == std::string::npos) {
throw std::invalid_argument("missing '=' in line: " + line);
}
std::cout << " parsed: " << line << std::endl;
}
void loadConfig() {
Guard g("loadConfig");
try {
parseLine("port=8080");
parseLine("timeout 30");
parseLine("debug=true"); // never reached
} catch (const std::exception& e) {
std::cout << " loadConfig logged: " << e.what() << std::endl;
throw; // rethrow the same exception
}
}
int main() {
try {
loadConfig();
} catch (const std::invalid_argument& e) {
std::cout << "main handled invalid_argument: " << e.what() << std::endl;
}
std::cout << "Program continues normally" << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- When the exception leaves
parseLine, its localGuardis destroyed first. This automatic cleanup on the way out is called stack unwinding. loadConfigcatches astd::exception&for logging, butthrow;rethrows the originalstd::invalid_argument, somaincan still catch the specific type.- Writing
throw e;instead would throw a copy of typestd::exception, losing the derived type (object slicing).
Exercise 67: Strong Exception Guarantee: Transaction Rollback
Practice Problem: Write a function transfer() that moves money between two accounts stored in a std::map. It must provide the strong exception guarantee: if any step fails, the accounts are left exactly as they were. Work on a copy and commit with swap() only when everything succeeds.
Given:
Accounts acc = {{"alice", 300}, {"bob", 120}};
Ops: alice->bob 100, bob->alice 500, alice->carol 50, bob->alice -5Code language: Python (python)
Expected Output:
OK: alice -> bob 100
alice: 200
bob: 220
FAILED: insufficient balance in bob
alice: 200
bob: 220
FAILED: unknown account in alice -> carol
alice: 200
bob: 220
FAILED: amount must be positive
alice: 200
bob: 220
+ Hint
- Copy the map, perform all changes on the copy, and throw if a rule is broken (unknown account, negative amount, insufficient balance).
- If no exception was thrown,
accounts.swap(copy)commits the changes.swapof two maps does not throw.
+ Show Solution
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
using Accounts = std::map<std::string, double>;
void transfer(Accounts& accounts, const std::string& from, const std::string& to, double amount) {
Accounts copy = accounts; // work on a copy
if (amount <= 0) throw std::invalid_argument("amount must be positive");
copy.at(from) -= amount; // at() throws if the account is missing
if (copy.at(from) < 0) throw std::runtime_error("insufficient balance in " + from);
copy.at(to) += amount;
accounts.swap(copy); // commit (noexcept)
}
void print(const Accounts& acc) {
for (const auto& [name, bal] : acc) std::cout << " " << name << ": " << bal << std::endl;
}
int main() {
Accounts acc = {{"alice", 300}, {"bob", 120}};
struct Op { std::string from, to; double amount; };
Op ops[] = {{"alice", "bob", 100}, {"bob", "alice", 500}, {"alice", "carol", 50}, {"bob", "alice", -5}};
for (const auto& op : ops) {
try {
transfer(acc, op.from, op.to, op.amount);
std::cout << "OK: " << op.from << " -> " << op.to << " " << op.amount << std::endl;
} catch (const std::out_of_range&) {
std::cout << "FAILED: unknown account in " << op.from << " -> " << op.to << std::endl;
} catch (const std::exception& e) {
std::cout << "FAILED: " << e.what() << std::endl;
}
print(acc);
}
return 0;
}Code language: C++ (cpp)
Explanation:
- In the third transfer, money is subtracted from “alice” in the copy before
at("carol")throws. Because only the copy was changed, the real accounts are untouched. - This copy, modify, swap pattern is the general recipe for the strong guarantee: all-or-nothing behavior.
std::map::at()throwsstd::out_of_rangefor a missing key, unlikeoperator[], which would silently create a new account.
Exercise 68: Write, Append, and Read a Text File
Practice Problem: Write a program that creates a text file notes.txt with std::ofstream, appends two more lines using std::ios::app, then reads it back with std::ifstream and prints each line with its line number along with the total number of lines, words, and characters.
Expected Output:
1: C++ file streams are easy
2: ofstream writes data
3: ifstream reads data
4: fstream can do both
Lines: 4, Words: 15, Characters (without newlines): 83
+ Hint
- Open for appending with
std::ofstream out("notes.txt", std::ios::app);. - Read line by line with
std::getline, and count words in each line withstd::istringstream.
+ Show Solution
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
int main() {
{
std::ofstream out("notes.txt"); // create / overwrite
out << "C++ file streams are easy" << std::endl;
out << "ofstream writes data" << std::endl;
} // file closed here (RAII)
{
std::ofstream out("notes.txt", std::ios::app); // append mode
out << "ifstream reads data" << std::endl;
out << "fstream can do both" << std::endl;
}
std::ifstream in("notes.txt");
if (!in) {
std::cout << "Cannot open notes.txt" << std::endl;
return 1;
}
std::string line;
int lines = 0, words = 0, chars = 0;
while (std::getline(in, line)) {
lines++;
chars += static_cast<int>(line.size());
std::istringstream iss(line);
std::string w;
while (iss >> w) words++;
std::cout << lines << ": " << line << std::endl;
}
std::cout << "Lines: " << lines << ", Words: " << words
<< ", Characters (without newlines): " << chars << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Each
std::ofstreamis placed in its own block, so the file is flushed and closed automatically at the closing brace before it is opened again. - Opening without
std::ios::apptruncates the file. Opening with it adds new data at the end. if (!in)checks whether the file opened successfully, which you should always do before reading.
Exercise 69: Parse a CSV File into Structs
Practice Problem: Write a CSV file employees.csv with a header row and five employee records (name, department, salary). Read it back, skip the header, parse each line with std::getline and a delimiter into a struct Employee, and print the total and average salary per department.
Expected Output:
Loaded 5 employees
Engineering total: 177000.00 average: 88500.00
HR total: 48000.00 average: 48000.00
Sales total: 113000.00 average: 56500.00
+ Hint
- Use
std::getline(ss, field, ',')on astd::stringstreamto split each line by commas. - Convert the salary text with
std::stod, and accumulate per department in astd::map<std::string, std::pair<double, int>>.
+ Show Solution
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
struct Employee {
std::string name, dept;
double salary;
};
int main() {
{
std::ofstream out("employees.csv");
out << "name,department,salary\n"
<< "Asha,Engineering,85000\n"
<< "Brian,Sales,52000\n"
<< "Chen,Engineering,92000\n"
<< "Dina,HR,48000\n"
<< "Eric,Sales,61000\n";
}
std::ifstream in("employees.csv");
std::string line;
std::getline(in, line); // skip header
std::vector<Employee> staff;
while (std::getline(in, line)) {
std::stringstream ss(line);
Employee e;
std::string salaryText;
std::getline(ss, e.name, ',');
std::getline(ss, e.dept, ',');
std::getline(ss, salaryText, ',');
e.salary = std::stod(salaryText);
staff.push_back(e);
}
std::map<std::string, std::pair<double, int>> byDept; // total, count
for (const auto& e : staff) {
byDept[e.dept].first += e.salary;
byDept[e.dept].second++;
}
std::cout << "Loaded " << staff.size() << " employees" << std::endl;
std::cout << std::fixed << std::setprecision(2);
for (const auto& [dept, data] : byDept) {
std::cout << std::left << std::setw(12) << dept
<< " total: " << data.first
<< " average: " << data.first / data.second << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
std::getlinewith a third argument reads up to that delimiter instead of a newline, which makes it a simple CSV splitter.- Reading the header line once before the loop prevents it from being parsed as data.
std::setwandstd::leftalign the department names into a neat column.
Exercise 70: Binary File I/O with Structs
Practice Problem: Define a struct Product with a fixed-size name (char[20]), an int id, and a double price. Write three products to products.bin in binary mode, then read back only the second record using seekg(), and finally read all records.
Given:
{"Keyboard", 101, 49.99}, {"Mouse", 102, 19.5}, {"Monitor", 103, 189.0}Code language: Python (python)
Expected Output:
Record #2 -> id: 102, name: Mouse, price: 19.5
All records:
101 Keyboard 49.99
102 Mouse 19.5
103 Monitor 189
+ Hint
- Open files with
std::ios::binaryand usewrite(reinterpret_cast<const char*>(&p), sizeof(p)). - Jump to record i with
in.seekg(i * sizeof(Product)). This works because every record has the same size.
+ Show Solution
#include <cstring>
#include <fstream>
#include <iostream>
struct Product {
char name[20];
int id;
double price;
};
Product make(const char* name, int id, double price) {
Product p{};
std::strncpy(p.name, name, sizeof(p.name) - 1);
p.id = id;
p.price = price;
return p;
}
int main() {
Product items[] = {make("Keyboard", 101, 49.99),
make("Mouse", 102, 19.5),
make("Monitor", 103, 189.0)};
{
std::ofstream out("products.bin", std::ios::binary);
for (const Product& p : items)
out.write(reinterpret_cast<const char*>(&p), sizeof(Product));
}
std::ifstream in("products.bin", std::ios::binary);
Product p{};
in.seekg(1 * sizeof(Product)); // jump to 2nd record
in.read(reinterpret_cast<char*>(&p), sizeof(Product));
std::cout << "Record #2 -> id: " << p.id << ", name: " << p.name << ", price: " << p.price << std::endl;
in.seekg(0); // back to start
std::cout << "All records:" << std::endl;
while (in.read(reinterpret_cast<char*>(&p), sizeof(Product))) {
std::cout << " " << p.id << " " << p.name << " " << p.price << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Binary files store the raw bytes of the struct, so reading and writing is fast and needs no parsing.
- Fixed-size records allow random access:
seekgjumps directly to any record without reading the ones before it. - This only works for simple (trivially copyable) structs. Never write a
std::stringor a pointer this way, because only the pointer value would be saved, not the text.
Exercise 71: Namespaces: Nested, Aliases, and Anonymous
Practice Problem: Organize geometry functions into nested namespaces Geometry::Circle and Geometry::Square, each with its own area() function. Use a namespace alias, a using declaration, and an anonymous namespace for a helper that should be private to the file.
Given:
double r = 3.0, s = 3.0;Code language: Python (python)
Expected Output:
Circle area (full name): 28.2743
Circle circumference (alias): 18.8495
Square area (using declaration): 9
Square perimeter: 12
PI from Geometry: 3.14159
+ Hint
- Since C++17 you can write nested namespaces in one line:
namespace Geometry::Circle { ... }. - An alias shortens long names:
namespace GC = Geometry::Circle;. Ausingdeclaration imports one name:using Geometry::Square::area;.
+ Show Solution
#include <iostream>
namespace {
// Anonymous namespace: visible only in this file
double square(double x) { return x * x; }
}
namespace Geometry {
constexpr double PI = 3.14159;
namespace Circle {
double area(double r) { return PI * square(r); }
double circumference(double r) { return 2 * PI * r; }
}
}
namespace Geometry::Square { // C++17 nested namespace definition
double area(double side) { return square(side); }
double perimeter(double side) { return 4 * side; }
}
namespace GC = Geometry::Circle; // namespace alias
int main() {
double r = 3.0, s = 3.0;
std::cout << "Circle area (full name): " << Geometry::Circle::area(r) << std::endl;
std::cout << "Circle circumference (alias): " << GC::circumference(r) << std::endl;
{
using Geometry::Square::area; // using declaration, limited to this block
std::cout << "Square area (using declaration): " << area(s) << std::endl;
}
std::cout << "Square perimeter: " << Geometry::Square::perimeter(s) << std::endl;
std::cout << "PI from Geometry: " << Geometry::PI << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- Both namespaces define a function called
area, and there is no conflict because each lives in its own scope. - The anonymous namespace gives
square()internal linkage, the modern replacement for marking a free functionstatic. - Placing the
usingdeclaration inside a block limits its effect. Avoidusing namespaceat global scope in headers, because it pulls every name into every file that includes them.
Exercise 72: Structured Bindings with Pairs, Tuples, and Maps
Practice Problem: Write a function minMaxAvg() that returns a std::tuple<int, int, double>. Unpack the result with structured bindings. Also use structured bindings to iterate over a std::map and to check the result of map::insert().
Given:
std::vector<int> temps = {18, 25, 21, 30, 16, 22};
std::map<std::string, int> stock = {{"apples", 12}, {"pears", 5}};Code language: Python (python)
Expected Output:
Low: 16, High: 30, Avg: 22
Insert plums: added plums
Insert apples: already exists with 12
apples = 12
pears = 5
plums = 9
+ Hint
auto [a, b, c] = someTuple;declares three variables from the tuple elements.map::insertreturns astd::pair<iterator, bool>. Unpack it asauto [it, inserted] = m.insert(...).
+ Show Solution
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <vector>
std::tuple<int, int, double> minMaxAvg(const std::vector<int>& v) {
int mn = v[0], mx = v[0];
double sum = 0;
for (int x : v) {
if (x < mn) mn = x;
if (x > mx) mx = x;
sum += x;
}
return {mn, mx, sum / v.size()};
}
int main() {
std::vector<int> temps = {18, 25, 21, 30, 16, 22};
auto [low, high, avg] = minMaxAvg(temps);
std::cout << "Low: " << low << ", High: " << high << ", Avg: " << avg << std::endl;
std::map<std::string, int> stock = {{"apples", 12}, {"pears", 5}};
auto [it, inserted] = stock.insert({"plums", 9});
std::cout << "Insert plums: " << (inserted ? "added " : "exists ") << it->first << std::endl;
auto [it2, inserted2] = stock.insert({"apples", 99});
std::cout << "Insert apples: " << (inserted2 ? "added" : "already exists with ") << it2->second << std::endl;
for (const auto& [fruit, qty] : stock) {
std::cout << fruit << " = " << qty << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
- Structured bindings (C++17) replace
std::get<0>(t)andpair.first/pair.secondwith meaningful names. insertnever overwrites an existing key, so “apples” keeps its value 12 andinserted2isfalse.- The braces in
return {mn, mx, sum / v.size()};construct the tuple directly from the declared return type.
Exercise 73: std::optional for Values That May Be Missing
Practice Problem: Write a function findUser(id) that searches a list of users and returns std::optional<User>: the user if found, or std::nullopt if not. Also write parseAge(text) that returns std::optional<int>, and use value_or() to supply defaults.
Given:
users = {{1, "Mila"}, {2, "Omar"}, {3, "Priya"}};
IDs to find: 2, 7
Ages to parse: "42", "abc", "", "200"Code language: Python (python)
Expected Output:
Found user 2: Omar
User 7 not found
parseAge("42") -> 42
parseAge("abc") -> -1
parseAge("") -> -1
parseAge("200") -> -1
+ Hint
- Return
std::nulloptto mean “no value”. Test the result withif (result)orresult.has_value(). opt.value_or(default)returns the stored value or the default when empty.
+ Show Solution
#include <iostream>
#include <optional>
#include <string>
#include <vector>
struct User {
int id;
std::string name;
};
const std::vector<User> users = {{1, "Mila"}, {2, "Omar"}, {3, "Priya"}};
std::optional<User> findUser(int id) {
for (const auto& u : users) {
if (u.id == id) return u;
}
return std::nullopt;
}
std::optional<int> parseAge(const std::string& text) {
if (text.empty()) return std::nullopt;
for (char c : text) {
if (c < '0' || c > '9') return std::nullopt;
}
int age = std::stoi(text);
if (age > 150) return std::nullopt;
return age;
}
int main() {
for (int id : {2, 7}) {
if (auto user = findUser(id)) {
std::cout << "Found user " << id << ": " << user->name << std::endl;
} else {
std::cout << "User " << id << " not found" << std::endl;
}
}
for (const char* input : {"42", "abc", "", "200"}) {
int age = parseAge(input).value_or(-1);
std::cout << "parseAge(\"" << input << "\") -> " << age << std::endl;
}
return 0;
}Code language: C++ (cpp)
Explanation:
std::optionalmakes “maybe no result” explicit in the function signature, instead of using special values like -1 or a null pointer.if (auto user = findUser(id))declares and tests the optional in one statement. Inside the block,user->nameaccesses the containedUser.value_or(-1)is a convenient way to fall back to a default when parsing fails.
Exercise 74: Type-Safe Unions with std::variant and std::visit
Practice Problem: Represent shapes as std::variant<Circle, Square, Triangle> (no inheritance). Store them in a vector and use std::visit with an overloaded set of lambdas to compute each area, and std::holds_alternative to count the circles.
Given:
Circle{1.0}, Square{3.0}, Triangle{4.0, 5.0}, Circle{2.0}Code language: Python (python)
Expected Output:
Circle (index 0) area = 3.14159
Square (index 1) area = 9
Triangle (index 2) area = 10
Circle (index 0) area = 12.5664
Total area: 34.7079
Number of circles: 2
+ Hint
- A small helper lets you combine several lambdas into one visitor:
template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; };plus a deduction guide. std::visit(visitor, v)calls the overload that matches the type currently stored inv.
+ Show Solution
#include <algorithm>
#include <iostream>
#include <variant>
#include <vector>
struct Circle { double r; };
struct Square { double side; };
struct Triangle { double base, height; };
using Shape = std::variant<Circle, Square, Triangle>;
template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template <class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main() {
std::vector<Shape> shapes = {Circle{1.0}, Square{3.0}, Triangle{4.0, 5.0}, Circle{2.0}};
auto areaOf = overloaded{
[](const Circle& c) { return 3.14159 * c.r * c.r; },
[](const Square& s) { return s.side * s.side; },
[](const Triangle& t) { return 0.5 * t.base * t.height; }
};
auto nameOf = overloaded{
[](const Circle&) { return "Circle"; },
[](const Square&) { return "Square"; },
[](const Triangle&) { return "Triangle"; }
};
double total = 0;
for (const auto& s : shapes) {
double a = std::visit(areaOf, s);
total += a;
std::cout << std::visit(nameOf, s) << " (index " << s.index() << ") area = " << a << std::endl;
}
std::cout << "Total area: " << total << std::endl;
auto circles = std::count_if(shapes.begin(), shapes.end(),
[](const Shape& s) { return std::holds_alternative<Circle>(s); });
std::cout << "Number of circles: " << circles << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
- A
std::variantholds exactly one of its listed types at a time and always knows which one, unlike a Cunion. - If you add a new type to the variant but forget a lambda for it,
std::visitfails at compile time, which makes this approach very safe. index()returns the position of the active type in the variant’s list, for example 0 forCircle.
Exercise 75: enum class, constexpr, and switch
Practice Problem: Model a traffic light with a scoped enumeration enum class Light { Red, Yellow, Green }. Write a constexpr function next() that returns the following state and a toString() function using switch. Also compute a factorial at compile time and verify it with static_assert.
Expected Output:
Step 0: RED (value 0)
Step 1: GREEN (value 2)
Step 2: YELLOW (value 1)
Step 3: RED (value 0)
Step 4: GREEN (value 2)
10! = 3628800
20! = 2432902008176640000
+ Hint
- Values of an
enum classare accessed asLight::Redand do not convert tointimplicitly. Usestatic_cast<int>when you need the number. - A
constexprfunction can be evaluated by the compiler when its arguments are constants, so it can be checked withstatic_assert.
+ Show Solution
#include <iostream>
enum class Light { Red, Yellow, Green };
constexpr Light next(Light l) {
switch (l) {
case Light::Red: return Light::Green;
case Light::Green: return Light::Yellow;
case Light::Yellow: return Light::Red;
}
return Light::Red;
}
const char* toString(Light l) {
switch (l) {
case Light::Red: return "RED";
case Light::Yellow: return "YELLOW";
case Light::Green: return "GREEN";
}
return "UNKNOWN";
}
constexpr unsigned long long factorial(int n) {
unsigned long long result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
static_assert(next(Light::Red) == Light::Green, "Red must turn Green");
static_assert(factorial(5) == 120, "5! must be 120");
int main() {
Light state = Light::Red;
for (int step = 0; step < 5; step++) {
std::cout << "Step " << step << ": " << toString(state)
<< " (value " << static_cast<int>(state) << ")" << std::endl;
state = next(state);
}
constexpr auto f10 = factorial(10); // computed at compile time
std::cout << "10! = " << f10 << std::endl;
std::cout << "20! = " << factorial(20) << std::endl;
return 0;
}Code language: C++ (cpp)
Explanation:
enum classprevents name clashes (two enums can both have aRed) and accidental comparisons with integers.- Because
switchlists every enumerator, compilers can warn you if a new light state is added but not handled. - The
static_assertlines are checked during compilation. Iffactorial(5)returned the wrong value, the program would not compile at all.

Leave a Reply