Start learning free

LESSON 188 OF 281 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in C++: Coupons with unordered_map

Practice Read the full explanation

Use a map as a fast lookup table for coupon discounts.

You start with:

int subtotal = 100;
string coupon = "SAVE20";
unordered_map<string, int> coupons = {{"SAVE10", 10}, {"SAVE20", 20}, {"SAVE50", 50}};

Build:

Total: $80

Rules:

  • Look up coupon in coupons. If it is there, its value is the discount; if it is not (an unknown code), the discount is 0.
  • total = subtotal - discount.
  • Build the text "Total: $<total>" (e.g. "Total: $80"; an unknown coupon would give "Total: $100").
  • Store it in result, then print it with cout << result << endl.

Use coupons.count(coupon) ? coupons[coupon] : 0: count tells you whether the key is present.

Use to_string(...) to turn each number into text before concatenating it to a string.

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;

STEP 1 OF 4
    Ctrl + Enter to check

    C++ · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in C++, explained

    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

    1. Create discount with coupons.count(coupon) ? coupons[coupon] : 0. The number 1 counts as true and 0 as false, so no comparison is needed.
    2. Create total as subtotal - discount.
    3. Create result from "Total: $" and to_string(total). The label is already text, so only the number is converted.
    4. Print result with cout and endl.

    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 : b evaluates to a when the condition is true and to b when it is false. Only the chosen side is evaluated, so coupons[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 an int) 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 up FREE with [] leaves a map of size 4 in which count("FREE") is now 1. A lookup should not change the table, which is the reason for the count check.
    • count doesn't insert. It only reports. After coupons.count("OTHER") the map still has the same size.
    • An alternative: find. auto it = coupons.find(coupon); returns an iterator, equal to coupons.end() when the key is missing. (it != coupons.end()) ? it->second : 0 gives the same discount and searches only once. For the code SAVE50 it gives 50, and for FREE it gives 0, with the map's size unchanged in both cases.
    • at throws. coupons.at("NOPE") throws std::out_of_range for 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 save20 in lowercase is a different key from SAVE20.

    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 FREE the program prints Total: $100.
    • A code in the wrong case. With save20 it also prints Total: $100, because the key is not found.
    • A discount larger than the subtotal. With a subtotal of 30 and SAVE50 the program prints Total: $-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: $" + total does not build the text. Use to_string(total).
    • Using [] as a membership test. It cannot tell "missing" from "present with value 0", and it inserts as a side effect.

    Testing

    subtotalcouponOutput
    100SAVE20Total: $80
    100FREETotal: $100
    100save20Total: $100
    30SAVE50Total: $-20

    The next version builds on this program.

    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free