This is the week's transfer task: a different tracker, built from a blank editor, with the same kinds of promises. An inventory stores items by stable positive ID with a quantity from 0 through 1000. Adding an existing ID fails without replacing it. A stock adjustment such as "-3" rejects missing IDs and any result outside the range, and a rejected adjustment leaves the old quantity. The inventory holds at most 100 items and reports total stock as a long. It also produces two outputs other code depends on: a low-stock report and a canonical export, so their exact order is part of the contract.
Notice what is different from the task tracker. Zero is a valid quantity here, while zero minutes was invalid; an out-of-stock item still exists. And an adjustment is arithmetic on stored data, so the rule is about the result, not just the input.
Acceptance cases: add ID 7 with 10 units, adjust by -3, then attempt -8. The quantity stays 7. Adding ID 7 again must not overwrite it. Add ID 2 with 5 units: total stock is 12. Adjusting a missing ID fails, and adjusting ID 2 by -5 to exactly 0 succeeds.
Report and export cases: in a separate inventory, add ID 5 with 3, ID 3 with 0, ID 8 with 3, ID 1 with 20 and ID 6 with 0, in that order. low_stock(3) returns the IDs with 3 or fewer units, lowest quantity first, ties broken by ID ascending: 3 6 5 8. low_stock(0) returns 3 6, and low_stock(-1) returns nothing. export_text() returns one id|quantity line per item in ID order, whatever order the items were added in, and a rejected adjustment leaves it byte-for-byte unchanged.
Predict and run
What does the subtraction give?
#include <iostream>
int main() {
int quantity = 10;
int change = -3;
std::cout << quantity + change << "\n";
return 0;
}Check your prediction
7The arithmetic is easy; the operation is not. A complete adjustment must also find the item, refuse a change so large that quantity + change could overflow an int (signed overflow is undefined behavior), check that the result is within 0 through 1000, and only then store it.
What you will use
- A class with private storage, so only member functions change stock (Days 1 and 2).
- An
enum class Errorwithnone,invalid,duplicate,missingandfull(Day 4). - Compute a candidate, validate it, then commit (Day 4).
std::optional<int>for a lookup that may find nothing, returned as a copy (Day 5).- A strict comparator with a tie-breaker for the report, checked against ties (Day 3).
- An exact-text test for the export, so a change in order or format fails (Day 6).
Plan before you type
- Write the contract as a list of cases first, including both ends of every range: quantity 0 and 1000, adjustment -1000 and 1000, the 100th and 101st item, and a tie in the report.
- Turn the cases into assertions before writing any member function.
- Build the members one at a time, running after each, and finish with the report and the export.
Prove it can fail
Break the solution on purpose and confirm an assertion stops the program each time. Assign found->second = next; before the range check: the rejected -8 now leaves -1 and the "stays 7" assertion fails. Replace find in adjust with stock_[id]: the missing-ID assertion fails, because a new item is created. Change next < 0 to next <= 0: the "exactly 0" assertion fails. Reverse the report's tie-breaker so equal quantities go by ID descending: the report becomes 6 3 8 5 and the exact-order assertion fails. Dropping the tie-breaker altogether is different: these tests cannot catch it. The map hands rows over already in ID order, and on inputs this small std::sort happens to leave equal rows where they were, so the report still reads 3 6 5 8. That is exactly why the contract states the tie-breaker: it makes the order a promise instead of luck. To prove the tie-breaker itself, a test has to feed the comparator rows out of ID order, which low_stock never does. If any of the other mutants still prints the success line, add the missing case.
Mistakes worth checking for
- A rejected adjustment changes the quantity: the assignment happened before validation.
- Adjusting a missing ID creates it:
operator[]inserted a default 0. - Zero stock is rejected: the range check copied the task tracker's "at least 1" rule.
- A huge adjustment gives a strange result:
quantity + changeoverflowed before it was checked. Bound the change first. - A duplicate add overwrites the quantity: insertion used
operator[]orinsert_or_assign. - The 101st item is accepted: the capacity check uses
>instead of>=.
Practice
Your turn
Implement Inventory with add, adjust, find, total, std::vector<int> low_stock(int threshold) const and std::string export_text() const. Reject adjustments outside -1000 through 1000 before adding, so arithmetic stays bounded. Assert every acceptance case, plus the 1000-unit maximum and the 100-item capacity, and every report and export case. Then print the low-stock report and the export for the second inventory, and a success line:
low stock (3 or fewer): 3 6 5 8
1|20
3|0
5|3
6|0
8|3
Inventory checks passed#include <algorithm>
#include <cassert>
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
enum class Error { none, invalid, duplicate, missing, full };
// Write Inventory here.
int main() {
return 0;
}Hint 1: the idea
Compute a candidate quantity and validate it before storing; every rejection returns before the single line that changes the stored data. Storage ordered by ID gives the export its order for free, while the report needs its own ordering rule, and that rule must say what happens when two quantities are equal.
Hint 2: a first step
Write add, find and total first, with the first acceptance case as assertions, and print the success line. Then add adjust and its cases. Leave the report until the stock rules pass, and start it by returning the matching IDs in ID order: the assertion for 3 6 5 8 then fails on the order alone, which is the comparator's job.
Show one solution
#include <algorithm>
#include <cassert>
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
enum class Error { none, invalid, duplicate, missing, full };
class Inventory {
public:
Error add(int id, int quantity) {
if (id < 1 || quantity < 0 || quantity > 1000) { return Error::invalid; }
if (stock_.find(id) != stock_.end()) { return Error::duplicate; }
if (stock_.size() >= 100) { return Error::full; }
stock_.emplace(id, quantity);
return Error::none;
}
Error adjust(int id, int change) {
auto found = stock_.find(id);
if (found == stock_.end()) { return Error::missing; }
if (change < -1000 || change > 1000) { return Error::invalid; }
const int next = found->second + change;
if (next < 0 || next > 1000) { return Error::invalid; }
found->second = next;
return Error::none;
}
std::optional<int> find(int id) const {
auto found = stock_.find(id);
if (found == stock_.end()) { return std::nullopt; }
return found->second;
}
long total() const {
long result = 0;
for (const auto& entry : stock_) { result += entry.second; }
return result;
}
// IDs with quantity <= threshold: lowest quantity first, ties by ID ascending.
std::vector<int> low_stock(int threshold) const {
std::vector<std::pair<int, int>> rows; // id, quantity
for (const auto& [id, quantity] : stock_) {
if (quantity <= threshold) { rows.emplace_back(id, quantity); }
}
std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) {
if (a.second != b.second) { return a.second < b.second; }
return a.first < b.first;
});
std::vector<int> ids;
for (const auto& row : rows) { ids.push_back(row.first); }
return ids;
}
// One "id|quantity" line per item, in ID order.
std::string export_text() const {
std::ostringstream out;
for (const auto& [id, quantity] : stock_) { out << id << '|' << quantity << '\n'; }
return out.str();
}
private:
std::map<int, int> stock_;
};
int main() {
Inventory inventory;
assert(inventory.add(7, 10) == Error::none);
assert(inventory.adjust(7, -3) == Error::none);
assert(inventory.adjust(7, -8) == Error::invalid);
assert(inventory.find(7) == 7);
assert(inventory.add(7, 99) == Error::duplicate && inventory.find(7) == 7);
assert(inventory.adjust(9, 1) == Error::missing && !inventory.find(9));
assert(inventory.add(2, 5) == Error::none);
assert(inventory.total() == 12);
assert(inventory.adjust(2, -5) == Error::none && inventory.find(2) == 0);
assert(inventory.adjust(7, 993) == Error::none && inventory.find(7) == 1000);
assert(inventory.adjust(7, 1) == Error::invalid);
assert(inventory.adjust(7, -2000000000) == Error::invalid && inventory.find(7) == 1000);
Inventory full;
for (int id = 1; id <= 100; ++id) { assert(full.add(id, 1000) == Error::none); }
assert(full.add(101, 1) == Error::full);
assert(full.total() == 100000L);
Inventory shop;
for (const auto& [id, quantity] : {std::pair{5, 3}, {3, 0}, {8, 3}, {1, 20}, {6, 0}}) {
assert(shop.add(id, quantity) == Error::none);
}
assert((shop.low_stock(3) == std::vector<int>{3, 6, 5, 8}));
assert((shop.low_stock(0) == std::vector<int>{3, 6}));
assert(shop.low_stock(-1).empty());
const std::string exported = shop.export_text();
assert(exported == "1|20\n3|0\n5|3\n6|0\n8|3\n");
assert(shop.adjust(1, -50) == Error::invalid && shop.export_text() == exported);
std::cout << "low stock (3 or fewer):";
for (int id : shop.low_stock(3)) { std::cout << ' ' << id; }
std::cout << "\n" << exported;
std::cout << "Inventory checks passed\n";
return 0;
}low stock (3 or fewer): 3 6 5 8
1|20
3|0
5|3
6|0
8|3
Inventory checks passedThe -2000000000 case would overflow found->second + change without the bound, so it proves the order of checks matters. Quantities 0 and 1000 are both reached and kept, and the 101st item is refused while the total of the full inventory, 100,000, shows why long is a comfortable choice. The report filters first and then sorts a small vector of copies, so it never reorders the stored map, and the tie-breaker makes the order of 3 and 6 a promise rather than an accident. The export needs no sort at all: the map is already in ID order, which is why the items were added out of order in the test. Comparing the export before and after a rejected adjustment checks every item at once. To go further, write a parser for id|quantity lines and test that importing the export rebuilds the same inventory, as Day 6 did.
Completion is saved in this browser only. It does not measure mastery.