Skip to content

Checkpoint: Update by ID

The Course
•
35 min study

This checkpoint puts today's pieces into one operation: change the duration of the task with a given ID. The operation has three possible outcomes, and each one has a rule. If the ID exists and the new duration is valid, exactly that entry changes. If the ID is missing, nothing changes and, in particular, no new entry appears. If the duration is invalid, nothing changes either. A function that only gets the first outcome right is the usual result of a quick implementation, so the tests you write matter as much as the code.

The outcomes are named with an enum class instead of returned as true or false. A caller that receives missing can say "no task 8"; a caller that receives false can only say "something went wrong".

Predict and run

The program updates one entry in place through the iterator find returned. What are the two numbers?

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

int main() {
    std::map<int, int> minutes{{2, 25}, {9, 10}};
    auto found = minutes.find(9);
    if (found != minutes.end()) { found->second = 20; }
    std::cout << minutes.find(2)->second << " " << minutes.find(9)->second << "\n";
    return 0;
}
Check your prediction
Text
25 20

found->second is a reference to the value stored in the map, not a copy, so assigning to it changes the map. Entry 2 is untouched. Change the lookup to find(8): the if is skipped, the map still has two entries, and find never inserted anything. The two ->second reads in the last line are safe only because both keys are known to exist; in general, check against end() first.

What you will use

  • std::map<int, Entry> keyed by task ID, where Entry holds a title and minutes.
  • find and end() to look up without inserting.
  • An iterator's ->second to change the stored entry in place.
  • enum class Update with updated, missing and invalid, so each outcome has a name.
  • A function that prints the whole map, so each test can show the complete state and not just one field.

Plan before you type

  1. Define Entry and enum class Update { updated, missing, invalid };.
  2. In update, call find(id) once and keep the iterator. Return missing if it equals end().
  3. Check the new minutes against 1 through 180 and return invalid before assigning anything.
  4. Only then assign found->second.minutes and return updated.
  5. In main, run four cases: a valid update of 9, an invalid update of 9, an update of the missing ID 8, and the boundary value 180 for ID 2. Print each outcome and the map after the last one.
Prove it can fail

Replace the find lookup with Entry& entry = values[id]; and run again. The missing-ID case now reports updated and the final listing grows a third row, 8: (30), with an empty title. That is the bug the missing check exists to catch. Then restore find and move the assignment above the range check: the invalid case must now leave 0 minutes in the listing. If your printed state does not change when the code is broken, add a case that would show it.

Mistakes worth checking for

  • A missing ID adds an empty entry: the code used operator[], which inserts a default value for an unknown key. Use find.
  • A rejected update still changed the value: the assignment happened before the validation. Decide first, then change.
  • The program crashes or prints nonsense for a missing ID: it read values.find(id)->second without comparing with end(), which is undefined behavior.
  • Every test passes but a wrong entry changed: the test only looked at the updated ID. Print or compare the whole map, so an edit to the wrong key shows up.
  • The caller cannot tell why an update failed: returning bool merges missing and invalid. Name each outcome.

Practice

Exercise

Your turn

Write Update update(std::map<int, Entry>& values, int id, int minutes). Start from {2, {"Read", 25}} and {9, {"Review", 10}} and run the four cases from the plan. Print each outcome with a helper that turns Update into text, then print the map:

Text
update 9 to 20: updated
update 9 to 0: invalid
update 8 to 30: missing
update 2 to 180: updated
2: Read (180)
9: Review (20)
Your workspace C++
#include <iostream>
#include <map>
#include <string>

struct Entry {
    std::string title;
    int minutes;
};

enum class Update { updated, missing, invalid };

// Write update and a name function for Update here.

int main() {
    std::map<int, Entry> values{{2, {"Read", 25}}, {9, {"Review", 10}}};
    return 0;
}
Hint 1: the idea

Find and validate before assigning. There are two reasons to refuse, and each must return before the one line that changes the map.

Hint 2: a first step

Begin with auto found = values.find(id); if (found == values.end()) { return Update::missing; }. The entry is then found->second, so its duration is found->second.minutes.

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

struct Entry {
    std::string title;
    int minutes;
};

enum class Update { updated, missing, invalid };

Update update(std::map<int, Entry>& values, int id, int minutes) {
    auto found = values.find(id);
    if (found == values.end()) { return Update::missing; }
    if (minutes < 1 || minutes > 180) { return Update::invalid; }
    found->second.minutes = minutes;
    return Update::updated;
}

const char* name(Update result) {
    switch (result) {
    case Update::updated: return "updated";
    case Update::missing: return "missing";
    case Update::invalid: return "invalid";
    }
    return "unknown";
}

void attempt(std::map<int, Entry>& values, int id, int minutes) {
    std::cout << "update " << id << " to " << minutes << ": " << name(update(values, id, minutes)) << "\n";
}

int main() {
    std::map<int, Entry> values{{2, {"Read", 25}}, {9, {"Review", 10}}};
    attempt(values, 9, 20);
    attempt(values, 9, 0);
    attempt(values, 8, 30);
    attempt(values, 2, 180);
    for (const auto& [id, entry] : values) {
        std::cout << id << ": " << entry.title << " (" << entry.minutes << ")\n";
    }
    return 0;
}
Text
update 9 to 20: updated
update 9 to 0: invalid
update 8 to 30: missing
update 2 to 180: updated
2: Read (180)
9: Review (20)

The final listing is the real evidence: two rows prove the missing ID inserted nothing, and 20 for task 9 proves the rejected 0 left the earlier update in place. The function checks existence before validity, so an update of a missing ID with a bad duration reports missing, which is the more useful message. Day 3 turns to reading many tasks at once: ranges, algorithms and sorted reports.

Was this article helpful?

Your response is saved on this device.