Use a map to accumulate totals per category while looping over parallel vectors, then list the categories sorted by name.
You start with:
vector<string> items = {"Apple", "Bread", "Shirt", "Banana", "Pants"};
vector<int> prices = {2, 3, 25, 1, 40};
vector<string> categories = {"Food", "Food", "Clothes", "Food", "Clothes"};
Build:
Clothes: $65 Food: $6
Rules:
- Build a
maptotalsthat maps each category to the sum of the prices of its items. - Loop with an index. For each item, add its price to the total of
categories[i]; a category you have not seen yet counts as 0. - Make one line per category, in the format
"Category: $total", sorted alphabetically by category name (soClothescomes beforeFood). - Join the lines with a newline
"\n"into one stringresult, then print it withcout << result << endl.
A
map<string, int> starts every new key at 0, so totals[cat] = totals[cat] + prices[i] just works.
A
map iterates in sorted key order automatically, so no extra sorting is needed.
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;
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
