Skip to content
Tutorials Center
My learning

Topics

Lesson 170 of 171 ยท Practice and Review

C++ Practice Exercises

29 graded C++ exercises with solutions on loops, functions, strings, vectors, maps, classes, templates, the STL and threads. Write and run C++ in your browser.

You learn C++ by writing C++. Reading lessons builds understanding, but only practice builds the reflexes: choosing the right container, getting a loop's bounds right the first time, knowing when to pass by const&. This page collects 29 exercises that cover the whole course, grouped by topic and ordered from beginner to advanced.

Every exercise has a short task, an editor with starter code, and a hidden solution. The starter code compiles and runs as given: functions you need to write are stubs that return a placeholder value, and the comments next to each test call show the output you should get. Replace the stub body, press Run, and compare.

  • Try first, peek later. Give each exercise a real attempt before opening the solution. A few minutes of being stuck is where the learning happens.
  • Compare, don't copy. Your solution can look different from ours and still be right. Read ours for ideas, then improve yours.
  • Watch the warnings. Our compiler runs with -Wall -Wextra, so it tells you about suspicious code. The stubs mark their parameters [[maybe_unused]] only so the empty versions compile without "unused parameter" warnings; delete the attribute once your code uses the parameter.

Each group links to the lessons it practices. Keep the cheat sheet open in another tab, and look at the 40 classic programs if you want worked examples first.

Basics and control flow

These practice printing output, reading input, if statements, for loops and while loops.

1. Temperature table (Beginner)

Print Celsius temperatures from 0 to 100 in steps of 20 next to their Fahrenheit values (F = C ร— 9 / 5 + 32). Right-align both columns under the headers and show one decimal place for Fahrenheit.

C++ Exercise 1: Temperature table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
for (int celsius = 0; celsius <= 100; celsius += 20) {
    double fahrenheit = celsius * 9.0 / 5 + 32;
    std::println("{:>7} {:>10.1f}", celsius, fahrenheit);
}

Writing 9.0 makes the multiplication floating point; with 9 / 5 in integer arithmetic you'd get 1 and every value would be wrong.

2. Clap-Snap (Beginner)

For the numbers 1 to 21, print Clap for multiples of 3, Snap for multiples of 7, ClapSnap for multiples of both, and the number itself otherwise. Print everything on one line, separated by spaces.

C++ Exercise 2: Clap-Snap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
for (int n = 1; n <= 21; ++n) {
    bool clap = n % 3 == 0;
    bool snap = n % 7 == 0;
    if (clap || snap) {
        std::print("{}{} ", clap ? "Clap" : "", snap ? "Snap" : "");
    } else {
        std::print("{} ", n);
    }
}

Computing both conditions first means "both" needs no special case: 21 prints both words in one call.

3. Letter grades (Beginner)

Write letter_grade(score) that returns 'A' for 90โ€“100, 'B' for 80โ€“89, 'C' for 70โ€“79, 'D' for 60โ€“69 and 'F' below 60. Scores outside 0โ€“100 return '?'. The program reads the scores from the Input box.

C++ Exercise 3: Letter grades

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
char letter_grade(int score) {
    if (score < 0 || score > 100) {
        return '?';
    }
    if (score >= 90) {
        return 'A';
    }
    if (score >= 80) {
        return 'B';
    }
    if (score >= 70) {
        return 'C';
    }
    if (score >= 60) {
        return 'D';
    }
    return 'F';
}

Rejecting invalid input first and then testing thresholds from the top down means each check only needs a lower bound.

4. Digital root (Intermediate)

Add up the digits of a number; if the result has more than one digit, repeat until one digit remains. For 98765: 9 + 8 + 7 + 6 + 5 = 35, then 3 + 5 = 8. Use % and /, not strings.

C++ Exercise 4: Digital root

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
int digital_root(long long number) {
    while (number >= 10) {
        long long sum = 0;
        for (; number > 0; number /= 10) {
            sum += number % 10;
        }
        number = sum;
    }
    return static_cast<int>(number);
}

The outer loop repeats while there's more than one digit, and the inner loop peels digits off with % 10 and / 10. (For positive numbers there's also a closed form: 1 + (n - 1) % 9.)

5. Collatz steps (Intermediate)

Starting from n, halve it when it's even and replace it with 3n + 1 when it's odd, until you reach 1. Return the number of steps. Starting at 6: 6 โ†’ 3 โ†’ 10 โ†’ 5 โ†’ 16 โ†’ 8 โ†’ 4 โ†’ 2 โ†’ 1 is 8 steps.

C++ Exercise 5: Collatz steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
int collatz_steps(long long n) {
    int steps = 0;
    while (n != 1) {
        n = n % 2 == 0 ? n / 2 : 3 * n + 1;
        ++steps;
    }
    return steps;
}

The conditional operator keeps the update on one line; long long matters because the values climb far above the starting number (27 peaks at 9,232).

Functions and recursion

These practice functions, parameters by reference and recursion.

6. Counting primes (Beginner)

Write is_prime(n), then use it in count_primes(low, high), which counts the primes in the inclusive range. Only test divisors up to the square root.

C++ Exercise 6: Counting primes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
bool is_prime(int n) {
    if (n < 2) {
        return false;
    }
    for (int d = 2; d * d <= n; ++d) {
        if (n % d == 0) {
            return false;
        }
    }
    return true;
}

int count_primes(int low, int high) {
    int count = 0;
    for (int n = low; n <= high; ++n) {
        if (is_prime(n)) {
            ++count;
        }
    }
    return count;
}

d * d <= n stops at the square root without floating-point math. For large ranges, the sieve in program 10 is much faster.

7. Tower of Hanoi (Intermediate)

Move discs discs from peg from to peg to, using spare, never placing a larger disc on a smaller one. Record each move as text like "A -> C". The recursive idea: move n โˆ’ 1 discs out of the way, move the largest disc, then move the n โˆ’ 1 discs on top of it.

C++ Exercise 7: Tower of Hanoi

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
void hanoi(int discs, char from, char to, char spare, std::vector<std::string>& moves) {
    if (discs == 0) {
        return;
    }
    hanoi(discs - 1, from, spare, to, moves);
    moves.push_back(std::format("{} -> {}", from, to));
    hanoi(discs - 1, spare, to, from, moves);
}

The base case is zero discs. Each level does two recursive calls plus one move, which is why n discs need 2โฟ โˆ’ 1 moves.

8. Sort three variables (Beginner)

Write sort3(a, b, c) that rearranges the caller's three variables so that a <= b <= c. The parameters must be references for the changes to be visible outside the function.

C++ Exercise 8: Sort three variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
void sort3(int& a, int& b, int& c) {
    if (a > b) {
        std::swap(a, b);
    }
    if (b > c) {
        std::swap(b, c);
    }
    if (a > b) {
        std::swap(a, b);
    }
}

Three compare-and-swap steps form a tiny sorting network: the second step moves the largest value into c, and the third fixes the order of the other two.

Strings

These practice strings, string methods, std::string_view and string streams.

9. Count words (Beginner)

Write count_words(text) that counts words separated by any number of spaces, tabs or newlines. Leading and trailing spaces must not create extra words.

C++ Exercise 9: Count words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
int count_words(std::string_view text) {
    int words = 0;
    bool in_word = false;
    for (char ch : text) {
        if (ch == ' ' || ch == '\t' || ch == '\n') {
            in_word = false;
        } else if (!in_word) {
            in_word = true;
            ++words;
        }
    }
    return words;
}

Counting the moments you enter a word, rather than counting spaces, makes repeated and trailing spaces harmless.

10. Caesar cipher (Intermediate)

Write caesar(text, shift) that shifts every letter by shift positions in the alphabet, wrapping around from z to a and keeping the case. Other characters stay as they are. A negative shift decodes.

C++ Exercise 10: Caesar cipher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::string caesar(std::string_view text, int shift) {
    int offset = (shift % 26 + 26) % 26;   // turns -3 into 23
    std::string result;
    result.reserve(text.size());
    for (char ch : text) {
        if (ch >= 'a' && ch <= 'z') {
            result += static_cast<char>('a' + (ch - 'a' + offset) % 26);
        } else if (ch >= 'A' && ch <= 'Z') {
            result += static_cast<char>('A' + (ch - 'A' + offset) % 26);
        } else {
            result += ch;
        }
    }
    return result;
}

Because % can return a negative number in C++, the offset is normalized into 0โ€“25 once, before the loop.

11. Reverse the words (Intermediate)

Write reverse_words(sentence) that returns the words in reverse order, separated by single spaces, with no leading or trailing spaces.

C++ Exercise 11: Reverse the words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::string reverse_words(const std::string& sentence) {
    std::istringstream stream(sentence);
    std::vector<std::string> words;
    for (std::string word; stream >> word; ) {
        words.push_back(word);
    }
    std::string result;
    for (auto it = words.rbegin(); it != words.rend(); ++it) {
        if (!result.empty()) {
            result += ' ';
        }
        result += *it;
    }
    return result;
}

>> on a string stream skips all whitespace for you, and reverse iterators walk the words from last to first.

12. Replace all (Intermediate)

Write replace_all(text, from, to) that replaces every occurrence of from with to. It must not loop forever when to contains from, and an empty from leaves the text unchanged.

C++ Exercise 12: Replace all

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::string replace_all(std::string text, std::string_view from, std::string_view to) {
    if (from.empty()) {
        return text;
    }
    std::size_t pos = 0;
    while ((pos = text.find(from, pos)) != std::string::npos) {
        text.replace(pos, from.size(), to);
        pos += to.size();   // continue AFTER the inserted text
    }
    return text;
}

Restarting the search after the replacement is what prevents the endless loop in "aaa" โ†’ "aaaaaa". Taking text by value gives the function its own copy to modify.

13. Longest common prefix (Intermediate)

Write common_prefix(words) that returns the longest prefix shared by every word, or an empty string if there is none or the list is empty.

C++ Exercise 13: Common prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::string common_prefix(const std::vector<std::string>& words) {
    if (words.empty()) {
        return "";
    }
    std::string prefix = words.front();
    for (const auto& word : words) {
        std::size_t length = 0;
        while (length < prefix.size() && length < word.size() && prefix[length] == word[length]) {
            ++length;
        }
        prefix.resize(length);
    }
    return prefix;
}

The candidate starts as the first word and only ever shrinks. Checking both lengths before indexing keeps every access in bounds.

Vectors and algorithms

These practice std::vector, multidimensional arrays, std::unordered_map and the modifying algorithms.

14. Running totals (Beginner)

Write running_totals(values) that returns a vector where each element is the sum of all values up to and including that position.

C++ Exercise 14: Running totals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::vector<int> running_totals(const std::vector<int>& values) {
    std::vector<int> totals;
    totals.reserve(values.size());
    int sum = 0;
    for (int v : values) {
        sum += v;
        totals.push_back(sum);
    }
    return totals;
}

reserve avoids reallocations because the final size is known. The standard library has this as std::partial_sum (or std::inclusive_scan) in <numeric>.

15. Move zeros to the end (Intermediate)

Write move_zeros_to_end(values) that moves every 0 to the end in place, keeping the other values in their original order. Don't create a second vector.

C++ Exercise 15: Move zeros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
void move_zeros_to_end(std::vector<int>& values) {
    std::size_t write = 0;
    for (int v : values) {
        if (v != 0) {
            values[write++] = v;
        }
    }
    while (write < values.size()) {
        values[write++] = 0;
    }
}

A "write index" trails the loop and compacts the non-zero values to the front, which is exactly how std::remove works internally. std::ranges::stable_partition with [](int v) { return v != 0; } is the one-line alternative.

16. Two sum (Intermediate)

Write two_sum(nums, target) that returns the indexes of two different elements that add up to target, or nothing if no pair exists. Aim for one pass with a hash map instead of checking every pair.

C++ Exercise 16: Two sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::optional<std::pair<std::size_t, std::size_t>> two_sum(const std::vector<int>& nums, int target) {
    std::unordered_map<int, std::size_t> seen;   // value -> index
    for (std::size_t i = 0; i < nums.size(); ++i) {
        if (auto it = seen.find(target - nums[i]); it != seen.end()) {
            return std::pair{it->second, i};
        }
        seen.emplace(nums[i], i);
    }
    return std::nullopt;
}

For each number, the partner you need is target - nums[i]; looking it up among earlier values makes the whole search O(n) on average instead of O(nยฒ). Searching before inserting stops an element from pairing with itself.

17. Spiral order (Advanced)

Write spiral(matrix) that returns the elements in clockwise spiral order: along the top row, down the right column, back along the bottom row, up the left column, then inward. It must work for matrices that aren't square.

C++ Exercise 17: Spiral order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::vector<int> spiral(const std::vector<std::vector<int>>& m) {
    std::vector<int> result;
    if (m.empty()) {
        return result;
    }
    int top = 0, bottom = static_cast<int>(m.size()) - 1;
    int left = 0, right = static_cast<int>(m[0].size()) - 1;
    while (top <= bottom && left <= right) {
        for (int c = left; c <= right; ++c) {
            result.push_back(m[top][c]);
        }
        ++top;
        for (int r = top; r <= bottom; ++r) {
            result.push_back(m[r][right]);
        }
        --right;
        if (top <= bottom) {
            for (int c = right; c >= left; --c) {
                result.push_back(m[bottom][c]);
            }
            --bottom;
        }
        if (left <= right) {
            for (int r = bottom; r >= top; --r) {
                result.push_back(m[r][left]);
            }
            ++left;
        }
    }
    return result;
}

Four shrinking boundaries describe the unvisited rectangle. The two extra checks stop a single leftover row or column from being walked twice, and signed int bounds avoid the unsigned wrap-around that right - 1 would cause at zero.

Maps and sets

These practice std::map, std::unordered_map and std::set.

18. Group anagrams (Intermediate)

Write group_anagrams(words) that groups words made of the same letters. Use each word's sorted letters as the key of a std::map, so the groups come out in key order.

C++ Exercise 18: Group anagrams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::map<std::string, std::vector<std::string>> group_anagrams(const std::vector<std::string>& words) {
    std::map<std::string, std::vector<std::string>> groups;
    for (const auto& word : words) {
        std::string key = word;
        std::ranges::sort(key);
        groups[key].push_back(word);
    }
    return groups;
}

Here operator[] inserting a missing key is exactly what you want: the first word of a group creates an empty vector, and every word is then appended to it.

19. First unique character (Intermediate)

Write first_unique(text) that returns the first character that appears exactly once, or nothing if every character repeats. Two passes are enough: count, then search.

C++ Exercise 19: First unique character

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::optional<char> first_unique(std::string_view text) {
    std::array<int, 256> counts{};
    for (char ch : text) {
        ++counts[static_cast<unsigned char>(ch)];
    }
    for (char ch : text) {
        if (counts[static_cast<unsigned char>(ch)] == 1) {
            return ch;
        }
    }
    return std::nullopt;
}

With only 256 possible byte values, a std::array counter is smaller and faster than a hash map. Casting to unsigned char keeps bytes above 127 from becoming negative indexes.

20. Common elements (Beginner)

Write common_elements(a, b) that returns the values present in both vectors, sorted and without duplicates.

C++ Exercise 20: Common elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::vector<int> common_elements(const std::vector<int>& a, const std::vector<int>& b) {
    std::set<int> left(a.begin(), a.end());
    std::set<int> right(b.begin(), b.end());
    std::vector<int> result;
    std::ranges::set_intersection(left, right, std::back_inserter(result));
    return result;
}

Building a std::set removes duplicates and sorts in one step, and set_intersection then merges the two sorted sequences in linear time.

Classes and object-oriented programming

These practice classes, operator overloading, virtual functions, std::unique_ptr and RAII.

21. A 2D vector type (Beginner)

Complete the Vec2 value type: operator+ and operator- combine two vectors, operator* scales a vector by a number, and length() returns its magnitude (the square root of xยฒ + yยฒ). Equality is already defaulted for you.

C++ Exercise 21: A 2D vector type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
double length() const { return std::hypot(x, y); }

Vec2 operator+(const Vec2& a, const Vec2& b) { return {a.x + b.x, a.y + b.y}; }
Vec2 operator-(const Vec2& a, const Vec2& b) { return {a.x - b.x, a.y - b.y}; }
Vec2 operator*(const Vec2& v, double factor) { return {v.x * factor, v.y * factor}; }

Free-function operators that return new values keep Vec2 a simple aggregate. std::hypot computes the square root of xยฒ + yยฒ without overflowing on large inputs.

22. Shapes and polymorphism (Intermediate)

Shape is an abstract base class. Implement area() and name() in Circle and Rectangle, then write total_area, which sums the areas through base-class pointers.

C++ Exercise 22: Shapes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
// In Circle:
double area() const override { return std::numbers::pi * radius_ * radius_; }
std::string name() const override { return "circle"; }

// In Rectangle:
double area() const override { return width_ * height_; }
std::string name() const override { return "rectangle"; }

double total_area(const std::vector<std::unique_ptr<Shape>>& shapes) {
    double total = 0;
    for (const auto& shape : shapes) {
        total += shape->area();
    }
    return total;
}

shape->area() dispatches to the right override at run time, and the virtual destructor in Shape lets each unique_ptr destroy its derived object correctly.

23. An RAII tracer (Intermediate)

Complete Trace so that creating one prints enter <name> and destroying it prints leave <name>, indented two spaces per nesting level. Use a static depth counter shared by all Trace objects, and forbid copying.

C++ Exercise 23: RAII tracer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
class Trace {
public:
    explicit Trace(std::string name) : name_(std::move(name)) {
        std::println("{}enter {}", std::string(depth_ * 2, ' '), name_);
        ++depth_;
    }
    ~Trace() {
        --depth_;
        std::println("{}leave {}", std::string(depth_ * 2, ' '), name_);
    }
    Trace(const Trace&) = delete;
    Trace& operator=(const Trace&) = delete;

private:
    std::string name_;
    inline static std::size_t depth_ = 0;
};

The destructor runs automatically at the end of each scope, even on an early return or an exception, which is the whole point of RAII. Deleting the copy operations stops a copy from printing a second leave.

Templates

These practice function templates, class templates and concepts.

24. A constrained largest() (Intermediate)

Write a function template largest(values) that returns the largest element of a vector, or nothing for an empty vector. Constrain T with std::totally_ordered so that calling it with a type that can't be compared fails with a clear error.

C++ Exercise 24: A constrained largest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
template <std::totally_ordered T>
std::optional<T> largest(const std::vector<T>& values) {
    if (values.empty()) {
        return std::nullopt;
    }
    T best = values.front();
    for (const T& value : values) {
        if (best < value) {
            best = value;
        }
    }
    return best;
}

The template is instantiated separately for int, std::string and double. Strings compare alphabetically, so "plum" beats "pear".

25. A fixed-capacity stack (Intermediate)

Complete the class template FixedStack<T, N>, a stack that stores at most N elements in a std::array. push returns false when the stack is full; pop returns the top element, or nothing when it's empty.

C++ Exercise 25: Fixed-capacity stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
bool push(const T& value) {
    if (count_ == N) {
        return false;
    }
    items_[count_++] = value;
    return true;
}
std::optional<T> pop() {
    if (count_ == 0) {
        return std::nullopt;
    }
    return items_[--count_];
}
std::size_t size() const { return count_; }
bool empty() const { return count_ == 0; }

N is a non-type template parameter, so the capacity is part of the type and the storage needs no heap allocation. Notice that main stores the three push results in variables first: in a single println call the evaluation order of the arguments is unspecified, and GCC happens to evaluate them right to left.

Advanced: STL, ranges and concurrency

These practice container adapters, lambdas, ranges, std::list and std::async.

26. Balanced brackets (Intermediate)

Write is_balanced(text) that checks whether every (, [ and { is closed by the matching bracket in the right order. Other characters are ignored. A std::stack of open brackets does most of the work.

C++ Exercise 26: Balanced brackets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
bool is_balanced(std::string_view text) {
    std::stack<char> open;
    for (char ch : text) {
        if (ch == '(' || ch == '[' || ch == '{') {
            open.push(ch);
        } else if (ch == ')' || ch == ']' || ch == '}') {
            char expected = ch == ')' ? '(' : ch == ']' ? '[' : '{';
            if (open.empty() || open.top() != expected) {
                return false;
            }
            open.pop();
        }
    }
    return open.empty();
}

A closing bracket must match the most recent unclosed opener, which is the top of the stack. Anything left on the stack at the end was never closed.

27. Top words (Advanced)

Write top_words(text, n) that returns the n most frequent words with their counts, ignoring case and punctuation. Sort by count (highest first) and break ties alphabetically.

C++ Exercise 27: Top words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
std::vector<std::pair<std::string, int>> top_words(const std::string& text, std::size_t n) {
    std::map<std::string, int> counts;
    std::string word;
    for (char ch : text + " ") {               // the extra space flushes the last word
        auto c = static_cast<unsigned char>(ch);
        if (std::isalpha(c)) {
            word += static_cast<char>(std::tolower(c));
        } else if (!word.empty()) {
            ++counts[word];
            word.clear();
        }
    }
    std::vector<std::pair<std::string, int>> result(counts.begin(), counts.end());
    std::ranges::stable_sort(result, std::ranges::greater{}, &std::pair<std::string, int>::second);
    result.resize(std::min(n, result.size()));
    return result;
}

The std::map delivers the words alphabetically, and a stable sort by count keeps that alphabetical order among equal counts, so no custom tie-breaking comparator is needed. The projection &pair::second tells the algorithm what to compare.

28. Parallel sum (Advanced)

Write parallel_sum(values, parts) that splits the vector into parts chunks, sums each chunk in its own task with std::async, and adds up the partial results. Use long long for the sums: the total doesn't fit in an int.

C++ Exercise 28: Parallel sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
long long parallel_sum(const std::vector<int>& values, unsigned parts) {
    parts = std::max(parts, 1u);
    std::vector<std::future<long long>> futures;
    std::size_t chunk = (values.size() + parts - 1) / parts;   // round up
    for (std::size_t start = 0; start < values.size(); start += chunk) {
        std::size_t end = std::min(start + chunk, values.size());
        futures.push_back(std::async(std::launch::async, [&values, start, end] {
            return std::accumulate(values.begin() + start, values.begin() + end, 0LL);
        }));
    }
    long long total = 0;
    for (auto& future : futures) {
        total += future.get();
    }
    return total;
}

Each task reads its own slice and writes nothing shared, so no mutex is needed; future.get() waits for the result. The initial value 0LL makes accumulate add in long long; with 0 it would overflow int.

29. An LRU cache (Advanced)

Implement LruCache, a cache that holds at most capacity key-value pairs. get returns a value and marks it as most recently used; put inserts or updates a value, and when the cache is full it first evicts the least recently used entry. Both operations should be O(1): combine a std::list (usage order) with a std::unordered_map (key to list position).

C++ Exercise 29: LRU cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Show solution
C++
class LruCache {
public:
    explicit LruCache(std::size_t capacity) : capacity_(capacity) {}

    std::optional<int> get(int key) {
        auto it = index_.find(key);
        if (it == index_.end()) {
            return std::nullopt;
        }
        items_.splice(items_.begin(), items_, it->second);   // mark as most recent
        return it->second->second;
    }

    void put(int key, int value) {
        if (auto it = index_.find(key); it != index_.end()) {
            it->second->second = value;
            items_.splice(items_.begin(), items_, it->second);
            return;
        }
        if (items_.size() == capacity_) {
            index_.erase(items_.back().first);              // evict least recent
            items_.pop_back();
        }
        items_.emplace_front(key, value);
        index_[key] = items_.begin();
    }

private:
    std::size_t capacity_;
    std::list<std::pair<int, int>> items_;   // most recent first
    std::unordered_map<int, std::list<std::pair<int, int>>::iterator> index_;
};

splice moves a list node to the front in O(1) without invalidating any iterators, so the iterators stored in the map stay valid. This is one of the few everyday cases where std::list is the right container.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In exercise 25, why can std::println("{} {}", stack.push(1), stack.push(2)) push the values in an unexpected order?

    C++ guarantees that each argument is fully evaluated before the call, but not in which order. GCC happens to go right to left; don't rely on any order when arguments have side effects.
  2. 2. In the Caesar cipher solution, why normalize the shift with (shift % 26 + 26) % 26?

    In C++, -3 % 26 is -3. Adding 26 and taking the remainder again maps every shift into the range 0 to 25.
  3. 3. What does std::accumulate(v.begin(), v.end(), 0) return for a vector of a million ints that add up to 500000500000?

    The type of the initial value decides the accumulator type. Passing 0LL makes it long long, which holds the result.
  4. 4. Why does the LRU cache store list iterators in its unordered_map?

    Searching the list would be O(n). list iterators stay valid when nodes are spliced, so the stored positions remain correct.

Summary

  • The basics exercises drill format specs, integer vs floating-point arithmetic, and loops whose bounds are right the first time.
  • Function exercises practice references for output parameters and recursion with a clear base case.
  • String exercises combine std::string_view parameters, find/replace, string streams and careful character handling.
  • Container exercises show when to reach for a hash map (two sum), a std::map (ordered groups), a std::set (unique sorted values) or a fixed array counter.
  • Class and template exercises build value types with operators, polymorphic hierarchies owned by std::unique_ptr, RAII objects and constrained templates.
  • The advanced exercises use a stack for matching, a stable sort with a projection, std::async for parallel work, and std::list::splice for an O(1) LRU cache.

Next: C++ Interview Questions, where you'll review the concepts behind these exercises the way interviewers ask about them.