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
couponincoupons. If it is there, its value is thediscount; if it is not (an unknown code), the discount is0. 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 withcout << 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;
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
