You need to enable JavaScript to run this app. 【C++】如何实现多字符串字符总频次统计、生成字符-频次对并升序排序?
优惠活动
大模型
产品
解决方案
定价
更多

【C++】如何实现多字符串字符总频次统计、生成字符-频次对并升序排序?

原实现的核心缺陷
  • 每处理完单个输入字符串就重置check_chars检查列表,统计逻辑完全被限定在单字符串范围内,没有跨字符串的频次累计逻辑,最终返回的vector里会出现多个同一字符的独立统计条目,无法完成合并
  • 自定义的isEqual函数返回字符本身的布尔值,完全不满足查找匹配的逻辑要求,后续find_if的调用逻辑无效,且直接输出迭代器值属于C++未定义行为
  • 缺失需求要求的“返回结果按字符升序排序”的逻辑
修正实现思路
  • 选用全局频次容器unordered_map<char, int>做跨字符串的统计:遍历所有输入字符串的每一个字符,直接在map中对对应字符的计数做累加,天然完成不同字符串的同一字符计数合并
  • 统计完成后将map中的键值对转换为要求的vector<pair<char, int>>格式
  • 对转换后的vector以字符字段为排序键做升序排列,直接满足返回格式要求
完整可运行修正代码
#include <iostream>
#include <vector>
#include <utility>
#include <string>
#include <unordered_map>
#include <algorithm>

using namespace std;

vector<pair<char, int>> all_occurrences(vector<string> vec) {
    unordered_map<char, int> total_freq;
    // 逐字符遍历所有输入字符串,累加总频次
    for (const string& str : vec) {
        for (char c : str) {
            total_freq[c]++;
        }
    }

    // 转换为目标pair vector结构
    vector<pair<char, int>> result;
    for (auto& item : total_freq) {
        result.emplace_back(item.first, item.second);
    }

    // 按字符升序排序
    sort(result.begin(), result.end(), [](const pair<char, int>& a, const pair<char, int>& b) {
        return a.first < b.first;
    });

    return result;
}

void print_vector(vector<pair<char, int>> pair_vector) {
    cout << "---" << endl;
    for (const auto& item : pair_vector) {
        cout << item.first << ',' << item.second << endl;
    }
    cout << "---" << endl;
}

int main() {
    vector<string> string_vector = {"ala", "ma", "kota"};
    print_vector(all_occurrences(string_vector));
    return 0;
}

逻辑优化说明:代码中逐字符累加的写法比原实现每遇到新字符就调用count()遍历全串的逻辑效率更高,时间复杂度为O(总字符数 + 字符集大小*log(字符集大小)),不存在重复遍历冗余。

测试输出

针对测试用例输入{"ala", "ma", "kota"},程序输出为:

---
a,4
k,1
l,1
m,1
o,1
t,1
---

完全匹配跨字符串累加统计、升序排序的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 16:54:11