Start learning free

LESSON 190 OF 667 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in C++: Category Totals with std::map

Practice Read the full explanation

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 map totals that 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 (so Clothes comes before Food).
  • Join the lines with a newline "\n" into one string result, then print it with cout << 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;

STEP 1 OF 12
    Ctrl + Enter to check

    C++ · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in C++, explained

    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 map keeps 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

    1. Create map<string, int> totals, empty.
    2. Loop over the items by index with i < (int)items.size(). The same i addresses the item's price and its category.
    3. Read the category into cat.
    4. 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.
    5. Create an empty vector<string> named lines after the loop.
    6. Loop over the map with for (auto &kv : totals). Each kv is a key-value pair: kv.first is the category and kv.second its total.
    7. Push one row per category onto lines, with the total turned into text by to_string.
    8. Create result as an empty string.
    9. Loop over lines by index.
    10. Add a newline before every row except the first, using if (i > 0).
    11. Append the row to result.
    12. Print result with cout and endl.

    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:

    iItemCategoryCategory total after the passCategories in the map
    0AppleFood21
    1BreadFood51
    2ShirtClothes252
    3BananaFood62
    4PantsClothes652

    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. auto lets the compiler deduce the element type, a pair<const string, int>. The & makes kv a reference, so the pair is not copied on every pass.
    • The key is const. You can't change kv.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, Office and clothes, the output lists them in exactly that order, so clothes comes last.
    • Names are exact. Food and food are different keys and get separate lines.
    • Why not unordered_map? It has no defined order, so the lines could come out in any order. Use map when 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, lines is empty and result is empty, so the program prints an empty line.
    • Inconsistent capitalisation. With categories clothes, Office and Clothes, three keys are created and clothes sorts after the capitalised ones.
    • Looping over the wrong thing. Looping over categories instead of the map would print one row per item, not one per category.
    • Index mismatch. Reading prices[i] and categories[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 40Clothes: $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 itemsan empty line
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free