Problem overview
The cart is described by three parallel vectors: items, prices and categories. Each item belongs to a category, and the program must print one line per category with the sum of its prices, in the form Category: $total, sorted alphabetically by category name. The lines are joined with newlines into result and printed.
With the starter data (Apple 2, Bread 3, Banana 1 in Food; Shirt 25 and Pants 40 in Clothes) the output is:
Clothes: $65
Food: $6
Approach: let a map accumulate and keep the order
The number of categories isn't known in advance, and items of one category are scattered through the vectors. A map<string, int> named totals fits: each category is a key and its running sum is the value. Two properties of std::map do the work:
- Reading a key that isn't there with
[]inserts it with the value 0. So the first item of a new category starts from 0 without any special case. - A
mapkeeps its keys sorted, so iterating over it visits the categories alphabetically. No sorting step is needed.
The program has three phases: accumulate by index, turn each map entry into a row, then join the rows.
Step by step
- Create
map<string, int> totals, empty. - Loop over the items by index with
i < (int)items.size(). The sameiaddresses the item's price and its category. - Read the category into
cat. - Update the total:
totals[cat] = totals[cat] + prices[i]. The right side reads the current sum (0 for a new category), and the left side stores the new one. - Create an empty
vector<string>namedlinesafter the loop. - Loop over the map with
for (auto &kv : totals). Eachkvis a key-value pair:kv.firstis the category andkv.secondits total. - Push one row per category onto
lines, with the total turned into text byto_string. - Create
resultas an empty string. - Loop over
linesby index. - Add a newline before every row except the first, using
if (i > 0). - Append the row to
result. - Print
resultwithcoutandendl.
The solution in C++
vector<string> items = {"Apple", "Bread", "Shirt", "Banana", "Pants"};
vector<int> prices = {2, 3, 25, 1, 40};
vector<string> categories = {"Food", "Food", "Clothes", "Food", "Clothes"};
map<string, int> totals;
for (int i = 0; i < (int)items.size(); i++) {
string cat = categories[i];
totals[cat] = totals[cat] + prices[i];
}
vector<string> lines;
for (auto &kv : totals) {
lines.push_back(kv.first + ": $" + to_string(kv.second));
}
string result = "";
for (int i = 0; i < (int)lines.size(); i++) {
if (i > 0) result += "\n";
result += lines[i];
}
cout << result << endl;
Following the accumulation
Printing the category's total after each pass of the first loop, with the starter data, gives:
| i | Item | Category | Category total after the pass | Categories in the map |
|---|---|---|---|---|
| 0 | Apple | Food | 2 | 1 |
| 1 | Bread | Food | 5 | 1 |
| 2 | Shirt | Clothes | 25 | 2 |
| 3 | Banana | Food | 6 | 2 |
| 4 | Pants | Clothes | 65 | 2 |
The map gains a key the first time each category appears, at i = 0 and i = 2, and only its value changes after that. Food's sum goes 2, 5, 6 and Clothes' goes 25, 65, each updated only on the passes that belong to it.
The last two loops then turn the finished map into text. The loop over totals visits Clothes first and Food second, so lines holds Clothes: $65 and Food: $6 in that order. The loop over lines joins them with a single newline between the two: a newline goes before every row except the first, so nothing trails after the last line. Then cout prints the result.
Details worth a closer look:
auto &kv.autolets the compiler deduce the element type, apair<const string, int>. The&makeskva reference, so the pair is not copied on every pass.- The key is
const. You can't changekv.first, because changing a key would break the map's order. - Sorted means by comparison of strings. The order is the string order: uppercase letters sort before lowercase ones. With the categories
Clothes,Officeandclothes, the output lists them in exactly that order, soclothescomes last. - Names are exact.
Foodandfoodare different keys and get separate lines. - Why not
unordered_map? It has no defined order, so the lines could come out in any order. Usemapwhen the output must be sorted. - Writing it as
totals[cat] += prices[i]is equivalent and shorter, and it also reads the current value once and stores the new one back.
Complexity
Time: O(n log k) for n items and k categories. Each [] lookup in a map costs O(log k), and the loop over the map and the join are linear in k.
Space: O(k) for the map and the rows, plus the output string.
Edge cases and common mistakes
- One category only. With Milk 2 and Egg 1 both in Food, the output is the single line
Food: $3, and the join adds no newline. - No items. The map stays empty,
linesis empty andresultis empty, so the program prints an empty line. - Inconsistent capitalisation. With categories
clothes,OfficeandClothes, three keys are created andclothessorts after the capitalised ones. - Looping over the wrong thing. Looping over
categoriesinstead of the map would print one row per item, not one per category. - Index mismatch. Reading
prices[i]andcategories[i]with different indexes would attach a price to the wrong category.
Testing
| Items (price, category) | Output |
|---|---|
| Apple 2, Bread 3, Shirt 25, Banana 1, Pants 40 | Clothes: $65, then Food: $6 |
| Milk 2, Egg 1 (both Food) | Food: $3 |
| Hat 10 (clothes), Pen 2 (Office), Cap 15 (Clothes) | Clothes: $15, Office: $2, clothes: $10 |
| No items | an empty line |
