You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用类中groupAna函数时如何用std::cout正确输出分组结果?

解决C++二维vector直接输出编译错误及分组验证问题

C++标准库没有为std::vector<std::vector<std::string>>类型提供默认的std::ostream重载,所以直接用std::cout输出会触发编译错误。要验证字母异位词的分组结果,你需要自己实现一个打印函数,来遍历并输出二维vector的层级结构。

步骤1:实现分组打印函数

写一个专门的辅助函数,遍历外层的分组容器,再逐个输出每个分组内的字符串:

#include <iostream>
#include <vector>
#include <string>

void printGroupedAnagrams(const std::vector<std::vector<std::string>>& groups) {
    for (size_t idx = 0; idx < groups.size(); ++idx) {
        std::cout << "分组 " << idx + 1 << ": [ ";
        for (const std::string& s : groups[idx]) {
            std::cout << "\"" << s << "\" ";
        }
        std::cout << "]\n";
    }
}

步骤2:完整代码示例

结合你的Solution类,完整可运行的代码如下(包含Group Anagrams的核心实现):

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

class Solution {
public:
    vector<vector<string>> groupAna(vector<string>& strs) {
        unordered_map<string, vector<string>> anagramMap;
        for (string& s : strs) {
            string sortedStr = s;
            sort(sortedStr.begin(), sortedStr.end());
            anagramMap[sortedStr].push_back(s);
        }
        vector<vector<string>> result;
        for (auto& entry : anagramMap) {
            result.push_back(entry.second);
        }
        return result;
    }
};

void printGroupedAnagrams(const vector<vector<string>>& groups) {
    for (size_t idx = 0; idx < groups.size(); ++idx) {
        cout << "分组 " << idx + 1 << ": [ ";
        for (const string& s : groups[idx]) {
            cout << "\"" << s << "\" ";
        }
        cout << "]\n";
    }
}

int main() {
    vector<string> testStrs = {"eat", "tea", "tan", "ate", "nat", "bat"};
    Solution sol;
    auto groupedResult = sol.groupAna(testStrs);
    printGroupedAnagrams(groupedResult);
    return 0;
}

预期输出效果

运行后会清晰展示每个分组的结构,类似:

分组 1: [ "eat" "tea" "ate" ]
分组 2: [ "tan" "nat" ]
分组 3: [ "bat" ]

这样你就能直观验证每个字母异位词是否被正确划分到对应的分组中。

内容的提问来源于stack exchange,提问作者TaeVon Lewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:55:19