Problem overview
The cart now holds several items, stored in three vectors that line up by position: items (names), prices and quantities. Position 0 of each vector describes the Shirt, position 1 the Pants, and so on. The program prints one receipt line per item in the form Name xQ: $subtotal, where the subtotal is the price times the quantity, and a final Total line. Everything is joined with newlines into one string, result.
The starter data produces:
Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195
The previous version handled one subtotal and shipping with an if/else. This one needs a loop.
Approach: collect rows, then join them
There are two jobs, and the lesson keeps them apart:
- Walk through the items by index. For each one, compute its subtotal, add it to a running
totaland store its receipt row in avector<string>calledlines. - Add the
Totalrow once, after the loop, because the total is only known when every item has been counted. - Join the rows into
resultwith a second loop, putting a newline between rows but not after the last one.
A loop by index is the right tool here because the three vectors share the same index i. A loop that visits only the names would not give you the matching price and quantity.
Step by step
- Create an empty
vector<string>namedlinesto hold the rows as they are made. - Create
totaland start it at 0. A running total always starts at zero. - Open a
forloop withifrom 0 whilei < (int)items.size(). - Compute
subasprices[i] * quantities[i]. - Add
subtototal. - Push this item's row onto
lines: the name, a space andx, the quantity, a colon and space, a dollar sign and the subtotal. The two numbers go throughto_string. - After the loop, push the Total row, using
totalturned into text. This line is outside the braces so it happens once. - Create
resultas an empty string. C++ has no ready-made join, so you build it yourself. - Loop over
linesby index, the same way as before. - Add a newline before every row except the first (
if (i > 0)), so rows are separated and nothing trails at the end. - Add the row itself to the end of
result. - Print
resultwithcoutandendl.
The solution in C++
vector<string> items = {"Shirt", "Pants", "Shoes", "Hat"};
vector<int> prices = {25, 40, 60, 15};
vector<int> quantities = {2, 1, 1, 3};
vector<string> lines;
int total = 0;
for (int i = 0; i < (int)items.size(); i++) {
int sub = prices[i] * quantities[i];
total = total + sub;
lines.push_back(items[i] + " x" + to_string(quantities[i]) + ": $" + to_string(sub));
}
lines.push_back("Total: $" + to_string(total));
string result = "";
for (int i = 0; i < (int)lines.size(); i++) {
if (i > 0) result += "\n";
result += lines[i];
}
cout << result << endl;
Details worth a closer look:
(int)items.size().size()returns an unsigned type, and comparing it with a signedintsuch asimakes the compiler warn. Casting the size tointkeeps the comparison between two signed numbers. It is safe here because the vectors are small.- Unsigned arithmetic is a trap. For an empty vector,
items.size() - 1does not give -1: it wraps around to 18446744073709551615 on a 64-bit build. The loop conditioni < (int)items.size()avoids subtraction altogether. - One expression builds the row.
items[i] + " x" + to_string(quantities[i]) + ": $" + to_string(sub)is evaluated left to right. It starts with astring, so every+after it joins a string with something that is already text. That is also why the name needs noto_string. push_backadds one element at the end of the vector, which then grows by one.- The one-line
if.if (i > 0) result += "\n";has no braces, so it controls only that single statement. The next line,result += lines[i];, runs every time.
How the running total grows
Printing i, the subtotal and the total after each pass of the first loop, with the starter data, shows how total builds up:
| i | Item | sub | total after the pass |
|---|---|---|---|
| 0 | Shirt | 50 | 50 |
| 1 | Pants | 40 | 90 |
| 2 | Shoes | 60 | 150 |
| 3 | Hat | 45 | 195 |
After the last pass, total holds 195, which is exactly what the final row needs. The Hat row shows why the multiplication matters: one hat costs 15, but three of them cost 45.
Complexity
Time: O(n) for n items. The first loop does a constant amount of work per item, and the second loop visits the n + 1 rows once each.
Space: O(n) for the lines vector, plus the output string, which grows with the number of rows.
Edge cases and common mistakes
- Putting the Total row inside the loop. It would be added once per item and show partial totals.
- Adding a newline after every row. The joined string would end with an extra newline, which then shows as an empty line after the output. The
i > 0test prevents that. - Forgetting to reset or initialise
total. An uninitialisedintholds an unspecified value. - Mixing up the indexes. Every vector must be read with the same
i, which is what ties a price to its name. - An empty cart. With three empty vectors the loops never run and the output is just
Total: $0.
Testing
| Cart | Output |
|---|---|
| Shirt 25 x2, Pants 40 x1, Shoes 60 x1, Hat 15 x3 | The five lines above, ending with Total: $195 |
| Pen 3 x4 | Pen x4: $12, then Total: $12 |
| No items | Total: $0 |
The next version builds on this program.
