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

字符数组转unordered_map再转大顶堆输出字符报错如何解决

问题排查与修复方案

核心错误点

  • 优先队列插入时键值对顺序写反
    你定义的priority_queue<pair<int, char>>要求第一个元素是排序用的频率值,第二个是对应字符,但你遍历unordered_map的时候,把代表字符的i->first作为pair第一个元素,代表频率的i->second作为第二个元素,最终排序依据变成了字符的ASCII码值,而非预期的频率值。
  • 仅输出了堆顶单个元素,没有遍历整个优先队列输出所有结果

修复后的代码

#include <bits/stdc++.h>
using namespace std;
int main()
{
    unordered_map<char, int> mp;
    priority_queue<pair<int, char>> mheap;

    char arr[] = {'a','a','a','b','c','c'};

    for (int i = 0; i < 6; ++i)
    {
        mp[arr[i]]++;
    }

    for (auto i = mp.begin(); i != mp.end(); i++)
    {
        // 调换pair两个参数顺序,频率在前,字符在后
        mheap.push({i->second, i->first});
    }

    // 循环弹出堆顶输出所有结果
    while(!mheap.empty()) {
        pair<int, char> curr = mheap.top();
        mheap.pop();
        cout << curr.second << " ";
    }

    return 0;
}

运行结果

修复后输出为a c b,完全符合按频率从高到低输出的预期逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:24:07