Question 8
Back to Exercise
Write an inventory using std::map<std::string, int> that processes sales and restocks, rejects sales of unknown or insufficient items, and prints a sorted report flagging items below 5.
Solution
#include <format>
#include <iostream>
#include <map>
#include <string>
#include <vector>
int main() {
std::map<std::string, int> stock{{"pen", 40}, {"notebook", 12}, {"bag", 6}, {"ruler", 3}};
struct Op { char type; std::string item; int qty; };
std::vector<Op> ops{{'S', "bag", 4}, {'S', "pen", 15}, {'S', "eraser", 1}, {'S', "ruler", 5}, {'R', "ruler", 10}, {'S', "notebook", 9}};
for (const auto& op : ops) {
auto it = stock.find(op.item);
if (op.type == 'R') { stock[op.item] += op.qty; continue; }
if (it == stock.end()) std::cout << "unknown item " << op.item << '\n';
else if (it->second < op.qty) std::cout << "not enough " << op.item << '\n';
else it->second -= op.qty;
}
for (const auto& [item, qty] : stock)
std::cout << std::format("{:<10}{:>3}{}\n", item, qty, qty < 5 ? " LOW" : "");
return 0;
}
unknown item eraser not enough ruler bag 2 LOW notebook 3 LOW pen 25 ruler 13
find() looks items up without inserting; operator[] is used only for restocks, where adding a new item is intended. The map keeps the report sorted.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!