Drill

ProblemsC++ › data

Totals per category

mediumdataHash mapsArraysC++

A ledger groups every sale under its category so each bucket shows a single sum.

sumPerCategory(sales: list<Sale>) → map<string, int>

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

std::map<std::string, int> sumPerCategory(std::vector<Sale> sales) {
    
}

Worked examples

CallResult
sumPerCategory(std::vector<Sale>{Sale{std::string("food"), 10}, Sale{std::string("food"), 15}})std::map<std::string, int>{{std::string("food"), 25}}
sumPerCategory(std::vector<Sale>{Sale{std::string("a"), 3}, Sale{std::string("b"), 4}, Sale{std::string("a"), 5}})std::map<std::string, int>{{std::string("a"), 8}, {std::string("b"), 4}}
sumPerCategory(std::vector<Sale>{Sale{std::string("x"), 1}})std::map<std::string, int>{{std::string("x"), 1}}
sumPerCategory(std::vector<Sale>{Sale{std::string("p"), 0}, Sale{std::string("q"), -2}})std::map<std::string, int>{{std::string("p"), 0}, {std::string("q"), -2}}

Hint

Aggregate into a map keyed by category, adding each amount as you go.

Reference solution in C++
std::map<std::string, int> sumPerCategory(std::vector<Sale> sales) {
    std::map<string, int> result;
    for (const auto& s : sales) result[s.category] += s.amount;
    return result;
}

The same problem in another language

More data problems in C++