Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,924 questions

51,857 answers

573 users

How to convert a vector of strings and group all the anagrams into subvectors in C++

1 Answer

0 votes
#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' ]
]

*/

 



answered Nov 14, 2025 by avibootz
...