Problem overview
The cart has a subtotal and the shopper typed a coupon code. The shop keeps its valid codes in an unordered_map<string, int> named coupons, where each code maps to the amount it takes off. The program looks the code up, subtracts the discount from the subtotal and prints one line, Total: $<total>, built in a string called result.
With a subtotal of 100 and the code SAVE20, the discount is 20 and the output is:
Total: $80
A code that isn't in the map takes nothing off: with FREE the discount is 0 and the total stays 100. The lesson is about that lookup, including what happens when the key is missing.
Approach: ask the map first, then read it
A map is a lookup table: you give it a key and it returns the value stored for that key, without scanning every entry. An unordered_map does this in constant time on average, however many coupons the shop has.
The catch is the missing key. The shopper can type anything, so the program has to handle codes that aren't in the table. The lesson's answer is to ask first and read second: coupons.count(coupon) returns the number of entries with that key, which for a map is 1 or 0. That fits the condition of a conditional (ternary) expression:
- if the count is 1, the discount is
coupons[coupon]; - otherwise the discount is 0.
From there the rest is arithmetic and formatting: subtract, turn the number into text, print.
Step by step
- Create
discountwithcoupons.count(coupon) ? coupons[coupon] : 0. The number 1 counts as true and 0 as false, so no comparison is needed. - Create
totalassubtotal - discount. - Create
resultfrom"Total: $"andto_string(total). The label is already text, so only the number is converted. - Print
resultwithcoutandendl.
The solution in C++
int subtotal = 100;
string coupon = "SAVE20";
unordered_map<string, int> coupons = {{"SAVE10", 10}, {"SAVE20", 20}, {"SAVE50", 50}};
int discount = coupons.count(coupon) ? coupons[coupon] : 0;
int total = subtotal - discount;
string result = "Total: $" + to_string(total);
cout << result << endl;
Details worth a closer look:
- The ternary operator.
condition ? a : bevaluates toawhen the condition is true and tobwhen it is false. Only the chosen side is evaluated, socoupons[coupon]is not touched for an unknown code. - Why not just write
coupons[coupon]? For a map,[]on a missing key inserts that key with a default value (0 for anint) and returns it. The answer for an unknown code would still be 0, but the map would quietly gain an entry. With the three starter coupons, looking upFREEwith[]leaves a map of size 4 in whichcount("FREE")is now 1. A lookup should not change the table, which is the reason for thecountcheck. countdoesn't insert. It only reports. Aftercoupons.count("OTHER")the map still has the same size.- An alternative:
find.auto it = coupons.find(coupon);returns an iterator, equal tocoupons.end()when the key is missing.(it != coupons.end()) ? it->second : 0gives the same discount and searches only once. For the codeSAVE50it gives 50, and forFREEit gives 0, with the map's size unchanged in both cases. atthrows.coupons.at("NOPE")throwsstd::out_of_rangefor a missing key, which is useful when a missing key is a bug rather than a normal case.- Keys are compared exactly. Strings match character for character, so
save20in lowercase is a different key fromSAVE20.
Complexity
Time: O(1) on average for the lookup, since a hash table finds a key without scanning the other entries. The rest of the program is a subtraction and a string build. The worst case for hashing is slower, but for a short table of coupons it does not matter.
Space: O(1) beyond the map itself.
Edge cases and common mistakes
- An unknown code. With
FREEthe program printsTotal: $100. - A code in the wrong case. With
save20it also printsTotal: $100, because the key is not found. - A discount larger than the subtotal. With a subtotal of 30 and
SAVE50the program printsTotal: $-20. The lesson's rules don't clamp the total at 0, so the subtraction is done as is. - Adding a number to text with
+."Total: $" + totaldoes not build the text. Useto_string(total). - Using
[]as a membership test. It cannot tell "missing" from "present with value 0", and it inserts as a side effect.
Testing
| subtotal | coupon | Output |
|---|---|---|
| 100 | SAVE20 | Total: $80 |
| 100 | FREE | Total: $100 |
| 100 | save20 | Total: $100 |
| 30 | SAVE50 | Total: $-20 |
The next version builds on this program.
