Question 10
Back to Exercise
Write a function template group_by(items, key_fn) that returns a std::map from key to vector of items, and use it with lambdas to group words by first letter and numbers by remainder.
Solution
#include <iostream>
#include <map>
#include <string>
#include <vector>
template <typename T, typename KeyFn>
auto group_by(const std::vector<T>& items, KeyFn key) {
std::map<decltype(key(items[0])), std::vector<T>> groups;
for (const auto& x : items) groups[key(x)].push_back(x);
return groups;
}
int main() {
std::vector<std::string> words{"apple", "banana", "avocado", "cherry", "blueberry", "apricot"};
for (const auto& [letter, list] : group_by(words, [](const std::string& w) { return w[0]; })) {
std::cout << letter << ':';
for (const auto& w : list) std::cout << ' ' << w;
std::cout << '\n';
}
std::vector<int> nums{1, 2, 3, 4, 5, 6, 7, 8, 9};
for (const auto& [r, list] : group_by(nums, [](int n) { return n % 3; })) {
std::cout << "mod " << r << ':';
for (int n : list) std::cout << ' ' << n;
std::cout << '\n';
}
return 0;
}
a: apple avocado apricot b: banana blueberry c: cherry mod 0: 3 6 9 mod 1: 1 4 7 mod 2: 2 5 8
The key lambda decides the grouping, and decltype(key(items[0])) makes the map's key type follow whatever the lambda returns (char, then int).
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!