#include <iostream>
#include <string>
#include <regex>
#include <unordered_map>
std::unordered_map<std::string, std::vector<std::string>>
group_by_first_n_letters(const std::string& s, std::size_t n = 3)
{
std::unordered_map<std::string, std::vector<std::string>> groups;
std::regex word_regex("[A-Za-z]+");
auto words_begin = std::sregex_iterator(s.begin(), s.end(), word_regex);
auto words_end = std::sregex_iterator();
for (auto it = words_begin; it != words_end; ++it) {
std::string w = it->str();
std::transform(w.begin(), w.end(), w.begin(), ::tolower);
if (w.size() >= n) {
groups[w.substr(0, n)].push_back(w);
}
}
return groups;
}
int main() {
std::string s = "The lowly inhabitants of the lowland were surprised to see "
"the lower branches of the trees.";
auto groups = group_by_first_n_letters(s, 3);
for (const auto& [prefix, words] : groups) {
std::cout << prefix << ": ";
for (const auto& w : words) std::cout << w << " ";
std::cout << "\n";
}
}
/*
run:
bra: branches
see: see
sur: surprised
tre: trees
wer: were
inh: inhabitants
low: lowly lowland lower
the: the the the the
*/