LearnFrenzy
Sign in Take a free test

STL Containers · STL Container Programs · Question 3

Group anagrams using a map of sorted keys in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Group words that are anagrams of each other, using the sorted letters of each word as a map key; print groups in key order.

Solution
main.cpp
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words{"listen", "silent", "enlist", "google", "inlets", "cat", "act", "tac", "dog"};
    std::map<std::string, std::vector<std::string>> groups;
    for (const auto& w : words) {
        std::string key = w;
        std::sort(key.begin(), key.end());
        groups[key].push_back(w);
    }
    for (const auto& [key, list] : groups) {
        std::cout << key << ':';
        for (const auto& w : list) std::cout << ' ' << w;
        std::cout << '\n';
    }
    return 0;
}

Output Verified by compiling and running

act: cat act tac
dgo: dog
eggloo: google
eilnst: listen silent enlist inlets

Anagrams share the same sorted letters, so they land under the same key. Here operator[] creating an empty vector on first use is exactly what we want.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links