Drill

ProblemsC++ › data

How many of each

easydataHash mapsArraysC++

A survey tallies how often each answer was given.

groupSizes(values: list<string>) → 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> groupSizes(std::vector<std::string> values) {
    
}

Worked examples

CallResult
groupSizes(std::vector<std::string>{std::string("a"), std::string("b"), std::string("a")})std::map<std::string, int>{{std::string("a"), 2}, {std::string("b"), 1}}
groupSizes(std::vector<std::string>{std::string("x")})std::map<std::string, int>{{std::string("x"), 1}}
groupSizes(std::vector<std::string>{std::string("p"), std::string("p"), std::string("p")})std::map<std::string, int>{{std::string("p"), 3}}
groupSizes(std::vector<std::string>{std::string("a"), std::string("b"), std::string("c")})std::map<std::string, int>{{std::string("a"), 1}, {std::string("b"), 1}, {std::string("c"), 1}}

Hint

Add one to the map entry for each value you meet.

Reference solution in C++
std::map<std::string, int> groupSizes(std::vector<std::string> values) {
    std::map<string, int> result;
    for (const auto& v : values) result[v]++;
    return result;
}

The same problem in another language

More data problems in C++