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?
#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
25 20found->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, whereEntryholds a title and minutes.findandend()to look up without inserting.- An iterator's
->secondto change the stored entry in place. enum class Updatewithupdated,missingandinvalid, 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
- Define
Entryandenum class Update { updated, missing, invalid };. - In
update, callfind(id)once and keep the iterator. Returnmissingif it equalsend(). - Check the new minutes against 1 through 180 and return
invalidbefore assigning anything. - Only then assign
found->second.minutesand returnupdated. - 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. Usefind. - 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)->secondwithout comparing withend(), 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
boolmergesmissingandinvalid. Name each outcome.
Practice
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:
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)#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
#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;
}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.
Completion is saved in this browser only. It does not measure mastery.