#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm> // sort
// Groups a vector of strings into sub-vectors of anagrams.
std::vector<std::vector<std::string>> groupAnagrams(const std::vector<std::string>& words) {
std::unordered_map<std::string, std::vector<std::string>> map;
for (const auto& word : words) {
// Sort characters
std::string sortword = word;
std::sort(sortword.begin(), sortword.end());
// Group words by their sorted key
map[sortword].push_back(word);
}
// Return grouped anagrams as a vector of vectors
std::vector<std::vector<std::string>> result;
for (auto& kv : map) {
result.push_back(std::move(kv.second));
}
return result;
}
int main() {
try {
std::vector<std::string> arr = {"eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"};
auto result = groupAnagrams(arr);
// Print result
std::cout << "[\n";
for (const auto& group : result) {
std::cout << " [ ";
for (size_t i = 0; i < group.size(); ++i) {
std::cout << "'" << group[i] << "'";
if (i + 1 < group.size()) std::cout << ", ";
}
std::cout << " ]\n";
}
std::cout << "]\n";
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
}
}
/*
run:
[
[ 'eat', 'tea', 'ate' ],
[ 'rop', 'orp', 'pro' ],
[ 'nat', 'tan' ],
[ 'bat' ]
]
*/