Skip to content

Assemble the Task Tracker

The Course
•
30 min study

The tracker is three files, and each has one job. Splitting them this way means the rules live in one place, the tests can use exactly the code the application uses, and you can read any one file without the others.

  • tracker.h declares the domain types (State, Error, Task, ParseResult), the Tracker interface, and the total_minutes_if template. The template is defined here because every file that calls it must see its body (Day 6). Comments next to each declaration state the contract: what is borrowed, what is owned, and what a rejection preserves.
  • tracker.cpp implements validation, parsing, updates and reports. Its helpers valid_fields and decimal are static, which keeps them private to this file.
  • main.cpp reads lines from standard input, counts rejections and prints the report. It is the only file that does input and output; the library returns values and Error codes and never prints (Day 4).

Each executable has exactly one main: the application links main.cpp with tracker.cpp, and the tests link test_tracker.cpp with tracker.cpp instead.

How the pieces enforce the week's rules

Read tracker.cpp with these decisions in mind:

  • One validation rule. Task::create and Task::edit both call valid_fields, so the duration, state and title rules exist once. The constructor is private, so every Task passed through create (Day 1).
  • Parse in two stages. parse_task first counts separators (malformed), then checks fields (invalid). It borrows the line as a std::string_view only during the call and builds an owning std::string for the title before returning (Day 5).
  • Overflow is impossible by construction. decimal accepts digits only and then reads with std::istringstream, which fails cleanly for a number too large for int. That is why the test with 21 digits is rejected instead of wrapping.
  • Identity by key. Tracker stores a std::map<int, Task>. add validates the task again at the boundary (a moved-from task may not be valid), refuses duplicates before checking capacity, and uses emplace so nothing is overwritten (Day 2).
  • Copies out, never borrows. find returns std::optional<Task>, and snapshot returns a vector of copies, so callers cannot hold references into the map across a later change. report_order sorts its own snapshot with the strict comparator from Day 3.

The task limit bounds the totals, not the input size: the import loop still reads each line into a std::string, so a single enormous line can allocate a lot of memory. Running out of memory is outside the course's recovery contract.

Predict and run

The second emplace uses an existing key. What are the two numbers?

Predict before running C++
#include <iostream>
#include <map>

int main() {
    std::map<int,int> tasks;
    int rejected = 0;
    if (!tasks.emplace(2,25).second) { ++rejected; }
    if (!tasks.emplace(2,40).second) { ++rejected; }
    std::cout << tasks.find(2)->second << " " << rejected << "\n";
    return 0;
}
Check your prediction
Text
25 1

This is the import policy in miniature: the duplicate is counted as rejected, and the original duration survives. In the project, Tracker::add reports Error::duplicate instead of relying on emplace alone, because it must also refuse before the capacity check: a duplicate in a full tracker should be called a duplicate, not "full".

Run the complete tracker

The input below is prefilled with the sample from the brief. Predict the full output first, then run.

Task tracker C++
#include "tracker.h" #include <iostream> int main() { Tracker tracker; std::string line; std::size_t rejected = 0; while (std::getline(std::cin, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } ParseResult result = parse_task(line); if (!result.task || tracker.add(*result.task) != Error::none) { ++rejected; } } if (std::cin.bad()) { std::cerr << "Input error\n"; return 1; } for (const Task& task : report_order(tracker)) { std::cout << task.id() << ": " << task.title() << " (" << task.minutes() << ", " << (task.state() == State::todo ? "todo" : "done") << ")\n"; } const auto tasks = tracker.snapshot(); const long pending = total_minutes_if(tasks, [](const Task& t) { return t.state() == State::todo; }); const long completed = total_minutes_if(tasks, [](const Task& t) { return t.state() == State::done; }); std::cout << "Tasks: " << tracker.size() << "\nPending: " << pending << " minutes\nCompleted: " << completed << " minutes\nRejected: " << rejected << '\n'; if (!std::cout) { return 1; } return 0; } #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 2|25|todo|Read chapter 1|10|done|Review notes bad 2|40|todo|Duplicate 3|25|todo|Practice
Check your prediction
Text
2: Read chapter (25, todo)
3: Practice (25, todo)
1: Review notes (10, done)
Tasks: 3
Pending: 50 minutes
Completed: 10 minutes
Rejected: 2

Now change the input and predict each result before running:

  • Clear it entirely. No report lines, and all four counts are 0.
  • Put bad first. The rejected count is unchanged and every later line still loads, because a bad line never stops the loop.
  • Swap the lines for tasks 2 and 3. The report order does not change: it depends on duration and ID, not input order.
  • Add 0004|060|todo|Plan. It appears first, as 4: Plan (60, todo), with leading zeros gone.
  • Add 5|25|todo|Read with a trailing space. It is rejected by the title rule.

Editing and completing tasks are library operations; this import program deliberately has no command language, because none has been specified. The extension lesson shows how to call one from main.cpp.

Practice

Exercise

Your turn

Write Error add_unique(std::map<int, int>& tasks, int id, int minutes) with enum class Error { none, invalid, duplicate, full };. It rejects IDs outside 1 through 9999 and minutes outside 1 through 180 as invalid, then existing IDs as duplicate, then a map that already holds 3 entries as full. Starting from {2, 25}, run these calls and print:

Text
add 2,40: duplicate
add 9,0: invalid
add 9,10: none
add 4,30: none
add 2,99: duplicate
add 7,15: full
stored: 2:25 4:30 9:10
Your workspace C++
#include <iostream>
#include <map>

enum class Error { none, invalid, duplicate, full };

// Write add_unique here (capacity 3).

int main() {
    std::map<int, int> tasks{{2, 25}};
    return 0;
}
Hint 1: the idea

Validate first, then check for a duplicate, then check capacity, then insert without overwriting. The order decides which error a request with several problems reports.

Hint 2: a first step

Check tasks.contains(id) for the duplicate before tasks.size() >= 3, so add 2,99 in a full map still reports duplicate. Insert with emplace, never operator[].

Show one solution
Run the solution C++
#include <iostream>
#include <map>

enum class Error { none, invalid, duplicate, full };

Error add_unique(std::map<int, int>& tasks, int id, int minutes) {
    if (id < 1 || id > 9999 || minutes < 1 || minutes > 180) { return Error::invalid; }
    if (tasks.contains(id)) { return Error::duplicate; }
    if (tasks.size() >= 3) { return Error::full; }
    tasks.emplace(id, minutes);
    return Error::none;
}

const char* name(Error error) {
    switch (error) {
    case Error::none: return "none";
    case Error::invalid: return "invalid";
    case Error::duplicate: return "duplicate";
    case Error::full: return "full";
    }
    return "unknown";
}

int main() {
    std::map<int, int> tasks{{2, 25}};
    const int requests[][2] = {{2, 40}, {9, 0}, {9, 10}, {4, 30}, {2, 99}, {7, 15}};
    for (const auto& request : requests) {
        std::cout << "add " << request[0] << "," << request[1] << ": "
                  << name(add_unique(tasks, request[0], request[1])) << "\n";
    }
    std::cout << "stored:";
    for (const auto& [id, minutes] : tasks) { std::cout << ' ' << id << ':' << minutes; }
    std::cout << "\n";
    return 0;
}
Text
add 2,40: duplicate
add 9,0: invalid
add 9,10: none
add 4,30: none
add 2,99: duplicate
add 7,15: full
stored: 2:25 4:30 9:10

add 2,99 happens when the map is already full and still reports duplicate, which proves the check order matches Tracker::add. The stored listing shows that no rejected call changed anything: task 2 still has 25 minutes. The next lesson reads the project's tests and maps each promise to the assertion that proves it.

Was this article helpful?

Your response is saved on this device.