The best test of whether you understand a codebase is to extend it without breaking any of its promises. This lesson adds one operation to the tracker, "remove every finished task", and then shows how to build and run the whole project on your own machine.
The extension looks small, but it touches most of the week. It must change the tracker only through its public members, remove exactly the done tasks, leave every todo task untouched, report how many it removed, and be safe to call twice or on an empty tracker. And it has a trap: removing entries from a container while you walk over that same container.
Design the extension
The contract, as it will appear in tracker.h:
C++
// Removes every done task and returns how many it removed. Todo tasks are unchanged.int remove_done(Tracker& tracker);
It takes Tracker&, not const Tracker&, because it changes the tracker, and it is a free function rather than a member, so it can only use snapshot(), remove() and the rest of the public interface. If it compiles, it cannot break an invariant that Tracker protects.
The trap is the loop. The tracker's tasks live in a private map you cannot walk over directly. Even if you could, erasing the entry a loop is standing on invalidates the iterator the loop needs for its next step (Day 3). The project already offers a safe sequence to walk: snapshot() returns an owning vector of copies (Day 5), so removing tasks from the tracker cannot disturb it.
Write tests in test_tracker.cpp before trusting the function. Good cases use a fresh tracker, so they don't depend on what earlier tests did to tracker:
An empty tracker returns 0.
Two done tasks and one todo task, with a done task in the last position, return 2. This catches a loop that stops early or after the first removal.
The export afterward holds only the todo task, which proves nothing else changed.
A second call returns 0 and leaves the size at 1, which proves the operation is safe to repeat.
Predict and run
The same pattern on a plain map: collect the keys first, then erase. What does it print?
The second loop walks over ids, a separate vector, so erasing from done cannot invalidate it. Erasing key 1 while a loop over done itself stood on key 1 would be undefined behavior. snapshot() gives you the same separation for the tracker, with whole Task copies instead of bare keys.
Practice
Exercise
Add remove_done to the tracker
Add remove_done to the project in the tabs below, which hold the tracker and its test program. Your edits are saved in this browser.
Declare it in tracker.h with the contract comment above.
Define it in tracker.cpp.
In test_tracker.cpp, just before the success message, add the four cases from the design, using a new Tracker named cleanup with task 1 (Review, 10, done), task 2 (Read, 25, todo) and task 3 (Notes, 5, done).
When every assertion passes, the test program prints:
Text
Tracker checks passed
Then break your function on purpose, for example by returning after the first removal, and check that one of your assertions stops the run.
Your working space: tracker and testsC++#include "tracker.h"
#include <cassert>
#include <iostream>
#include <sstream>
int main() {
assert(!Task::create(0, "Read", 25, State::todo));
assert(!Task::create(10000, "Read", 25, State::todo));
assert(!Task::create(1, "", 25, State::todo));
assert(!Task::create(1, " Read", 25, State::todo));
assert(!Task::create(1, "Read ", 25, State::todo));
assert(!Task::create(1, "Bad|title", 25, State::todo));
assert(!Task::create(1, "Read", 0, State::todo));
assert(!Task::create(1, "Read", 181, State::todo));
assert(Task::create(9999, std::string(40, 'x'), 180, State::done));
assert(!Task::create(1, std::string(41, 'x'), 25, State::todo));
Tracker tracker;
assert(tracker.size() == 0 && !tracker.find(1));
auto first = Task::create(2, "Read", 25, State::todo);
auto second = Task::create(1, "Review", 10, State::done);
auto third = Task::create(3, "Practice", 25, State::todo);
assert(first && second && third);
assert(tracker.add(*first) == Error::none);
assert(tracker.add(*second) == Error::none);
assert(tracker.add(*third) == Error::none);
const std::string original = export_tasks(tracker);
assert(original == "1|10|done|Review\n2|25|todo|Read\n3|25|todo|Practice\n");
assert(tracker.add(*first) == Error::duplicate && export_tasks(tracker) == original);
assert(tracker.edit(2, "Changed", 0, State::done) == Error::invalid);
assert(export_tasks(tracker) == original);
assert(tracker.edit(99, "Missing", 20, State::todo) == Error::missing);
assert(tracker.complete(99) == Error::missing);
auto copy = tracker.find(2);
assert(copy && copy->edit("Copy", 50, State::done));
assert(tracker.find(2)->title() == "Read");
auto ordered = report_order(tracker);
assert(ordered[0].id() == 2 && ordered[1].id() == 3 && ordered[2].id() == 1);
assert(export_tasks(tracker) == original);
assert(total_minutes_if(ordered, [](const Task&) { return true; }) == 60);
assert(total_minutes_if(ordered, [](const Task& t) { return t.state() == State::todo; }) == 50);
assert(tracker.complete(2) == Error::none);
assert(tracker.complete(2) == Error::none);
assert(total_minutes_if(tracker.snapshot(), [](const Task& t) { return t.state() == State::todo; }) == 25);
assert(tracker.edit(2, "Updated", 40, State::todo) == Error::none);
assert(tracker.find(2)->title() == "Updated" && tracker.find(2)->minutes() == 40);
assert(tracker.find(2)->state() == State::todo);
const std::string canonical = export_tasks(tracker);
Tracker restored;
std::istringstream input(canonical);
std::string line;
while (std::getline(input, line)) {
auto result = parse_task(line);
assert(result.task && result.error == Error::none);
assert(restored.add(*result.task) == Error::none);
}
assert(export_tasks(restored) == canonical);
const std::vector<std::string> invalid{"", "1|25|todo", "1|25|later|Read", "1|25x|todo|Read",
"1|25|todo|Read|extra", "1|999999999999999999999|todo|Read", "-1|25|todo|Read", "1|25|todo|"};
for (const auto& text : invalid) { assert(!parse_task(text).task); }
assert(parse_task("bad").error == Error::malformed);
assert(parse_task("0|25|todo|Read").error == Error::invalid);
Task owned = *parse_task(std::string("9|1|todo|Temporary")).task;
assert(owned.title() == "Temporary");
assert(tracker.remove(1) == Error::none && !tracker.find(1));
assert(tracker.remove(1) == Error::missing);
assert(tracker.find(2)->id() == 2 && tracker.find(3)->id() == 3);
// A removed ID is free again: the brief promises no renumbering, not that IDs are retired.
assert(tracker.add(*Task::create(1, "Plan", 15, State::todo)) == Error::none);
assert(tracker.find(1)->title() == "Plan" && tracker.size() == 3);
assert(tracker.remove(1) == Error::none);
Tracker full;
for (int id = 1; id <= 1000; ++id) { assert(full.add(*Task::create(id, "Task", 180, State::todo)) == Error::none); }
assert(full.add(*Task::create(1001, "Extra", 1, State::todo)) == Error::full && full.size() == 1000);
assert(total_minutes_if(full.snapshot(), [](const Task&) { return true; }) == 180000L);
assert(export_tasks(Tracker{}).empty());
std::cout << "Tracker checks passed\n";
}
#include "tracker.h"
#include <algorithm>
#include <sstream>
#include <utility>
static bool valid_fields(const std::string& title, int minutes, State state) {
if (title.empty() || title.size() > 40 || minutes < 1 || minutes > 180 ||
(state != State::todo && state != State::done)) { return false; }
if (title.front() == ' ' || title.back() == ' ') { return false; }
for (unsigned char ch : title) {
if (ch < 32 || ch > 126 || ch == '|') { return false; }
}
return true;
}
Task::Task(int id, std::string title, int minutes, State state)
: id_(id), title_(std::move(title)), minutes_(minutes), state_(state) { }
std::optional<Task> Task::create(int id, std::string title, int minutes, State state) {
if (id < 1 || id > 9999 || !valid_fields(title, minutes, state)) { return std::nullopt; }
return Task(id, std::move(title), minutes, state);
}
bool Task::edit(std::string title, int minutes, State state) {
if (!valid_fields(title, minutes, state)) { return false; }
title_ = std::move(title);
minutes_ = minutes;
state_ = state;
return true;
}
static std::optional<int> decimal(std::string_view text) {
if (text.empty()) { return std::nullopt; }
for (char ch : text) { if (ch < '0' || ch > '9') { return std::nullopt; } }
std::istringstream input{std::string(text)};
int value = 0;
if (!(input >> value)) { return std::nullopt; }
return value;
}
ParseResult parse_task(std::string_view line) {
const auto first = line.find('|');
if (first == std::string_view::npos) { return {std::nullopt, Error::malformed}; }
const auto second = line.find('|', first + 1);
if (second == std::string_view::npos) { return {std::nullopt, Error::malformed}; }
const auto third = line.find('|', second + 1);
if (third == std::string_view::npos || line.find('|', third + 1) != std::string_view::npos) {
return {std::nullopt, Error::malformed};
}
auto id = decimal(line.substr(0, first));
auto minutes = decimal(line.substr(first + 1, second - first - 1));
auto state_text = line.substr(second + 1, third - second - 1);
if (!id || !minutes || (state_text != "todo" && state_text != "done")) {
return {std::nullopt, Error::invalid};
}
auto task = Task::create(*id, std::string(line.substr(third + 1)), *minutes,
state_text == "todo" ? State::todo : State::done);
if (!task) { return {std::nullopt, Error::invalid}; }
return {std::move(task), Error::none};
}
Error Tracker::add(const Task& task) {
if (!Task::create(task.id(), task.title(), task.minutes(), task.state())) { return Error::invalid; }
if (tasks_.find(task.id()) != tasks_.end()) { return Error::duplicate; }
if (tasks_.size() >= 1000) { return Error::full; }
tasks_.emplace(task.id(), task);
return Error::none;
}
Error Tracker::edit(int id, std::string title, int minutes, State state) {
auto it = tasks_.find(id);
if (it == tasks_.end()) { return Error::missing; }
return it->second.edit(std::move(title), minutes, state) ? Error::none : Error::invalid;
}
Error Tracker::complete(int id) {
auto it = tasks_.find(id);
if (it == tasks_.end()) { return Error::missing; }
it->second.edit(it->second.title(), it->second.minutes(), State::done);
return Error::none;
}
Error Tracker::remove(int id) {
return tasks_.erase(id) == 0 ? Error::missing : Error::none;
}
std::optional<Task> Tracker::find(int id) const {
auto it = tasks_.find(id);
if (it == tasks_.end()) { return std::nullopt; }
return it->second;
}
std::vector<Task> Tracker::snapshot() const {
std::vector<Task> result;
for (const auto& entry : tasks_) { result.push_back(entry.second); }
return result;
}
std::vector<Task> report_order(const Tracker& tracker) {
auto tasks = tracker.snapshot();
std::sort(tasks.begin(), tasks.end(), [](const Task& a, const Task& b) {
if (a.minutes() != b.minutes()) { return a.minutes() > b.minutes(); }
return a.id() < b.id();
});
return tasks;
}
std::string export_tasks(const Tracker& tracker) {
std::ostringstream output;
for (const Task& task : tracker.snapshot()) {
output << task.id() << '|' << task.minutes() << '|'
<< (task.state() == State::todo ? "todo" : "done") << '|' << task.title() << '\n';
}
return output.str();
}
#ifndef TASK_TRACKER_H
#define TASK_TRACKER_H
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
enum class State { todo, done };
enum class Error { none, malformed, invalid, duplicate, missing, full };
class Task {
public:
static std::optional<Task> create(int id, std::string title, int minutes, State state);
int id() const { return id_; }
const std::string& title() const { return title_; } // Borrowed until this task changes/dies.
int minutes() const { return minutes_; }
State state() const { return state_; }
bool edit(std::string title, int minutes, State state); // Invalid edits preserve all fields.
private:
Task(int id, std::string title, int minutes, State state);
int id_;
std::string title_;
int minutes_;
State state_;
};
struct ParseResult { std::optional<Task> task; Error error = Error::none; };
// id|minutes|todo-or-done|title. Numeric fields contain decimal digits only.
// CRLF stripping belongs to the input adapter. No embedded control characters.
ParseResult parse_task(std::string_view line);
class Tracker {
public:
Error add(const Task& task); // 1000 tasks maximum; duplicates leave existing task unchanged.
Error edit(int id, std::string title, int minutes, State state);
Error complete(int id); // Repeating completion succeeds without changing totals twice.
Error remove(int id);
std::optional<Task> find(int id) const; // Returns an owning copy.
std::vector<Task> snapshot() const; // ID order; owning values.
std::size_t size() const { return tasks_.size(); }
private:
std::map<int, Task> tasks_;
};
// Owns its return value. Input text/view may be destroyed after parsing.
std::string export_tasks(const Tracker& tracker);
std::vector<Task> report_order(const Tracker& tracker); // Minutes descending, then ID ascending.
template<class Predicate>
long total_minutes_if(const std::vector<Task>& tasks, Predicate matches) {
long total = 0;
for (const Task& task : tasks) {
if (matches(task)) { total += task.minutes(); }
}
return total;
}
#endif
Hint 1: the idea
Walk over a copy, change the original. Every task in the snapshot is a candidate; the ones whose state is done get removed from the tracker by ID, and each successful removal adds one to the count.
Hint 2: a first step
Write the declaration and a definition that returns 0 without removing anything, then add the test with the three tasks and assert(remove_done(cleanup) == 2);. Run: that assertion fails, which proves the test can catch a do-nothing version. Now fill in the body.
Show one solution
In tracker.h, before the total_minutes_if template:
C++
// Removes every done task and returns how many it removed. Todo tasks are unchanged.int remove_done(Tracker& tracker);
At the end of tracker.cpp:
C++
int remove_done(Tracker& tracker) { int removed = 0; for (const Task& task : tracker.snapshot()) { if (task.state() == State::done && tracker.remove(task.id()) == Error::none) { ++removed; } } return removed;}
In test_tracker.cpp, before std::cout << "Tracker checks passed\n";:
The loop's range is the temporary vector snapshot() returns, which lives until the loop ends, so removing from the tracker inside the loop is safe. Counting only when remove returns Error::none makes the result honest even if a future remove can refuse. The export comparison checks every field of the surviving task at once, the same full-state evidence the week has used for rejected edits. In the next lesson you design a different tracker on your own.
Optional local setup
Download the C++ task tracker. It includes the maintained header, implementation, application, tests, mutation manifest, sample input and README. Browser edits are not included; copy your extension from the tabs above into the extracted files to keep it.
Install a C++20-capable Clang or GCC compiler (macOS Command Line Tools, a Linux compiler package, or Windows MSYS2). In a POSIX terminal inside the extracted folder:
-Wall -Wextra -Wpedantic turn on the common warnings, and -Werror makes any warning stop the build, so a warning cannot scroll past unread.
Compile the application and the tests separately because each has its own main. Keep assertions enabled: do not define NDEBUG. Windows may add .exe to executable names; the shell commands work in the MSYS2 terminal. All required course work runs in the browser.
Going further
Build the tests once with -g -fsanitize=address,undefined -fno-omit-frame-pointer when your compiler supports it. The sanitizers turn silent undefined behavior, such as reading a dangling view or overflowing an int, into an immediate report with a line number. A debugger can stop just before a rejected edit so you can inspect the candidate and the original fields. Exceptions, threads, inheritance, custom allocators, advanced templates and std::expected are later topics. The browser currently excludes exceptions and threads; this is a runtime limit rather than a limitation of C++.
Completion is saved in this browser only. It does not measure mastery.