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

C++如何按值对map进行降序排序?

按值对Map进行降序排序的实现方法

修改原有比较函数实现降序

原代码的cmp函数通过a.second < b.second实现升序排序,只需将比较符号改为>就能直接实现降序:

bool cmp(pair<string, int>& a,
         pair<string, int>& b)
{
    return a.second > b.second; // 仅修改此处,升序转降序
}
  
void sort(map<string, int>& M)
{
    vector<pair<string, int>> A;
  
    for (auto& it : M) 
        A.push_back(it);
  
    sort(A.begin(), A.end(), cmp);
    
    // 可添加遍历逻辑查看结果,比如输出键值对
    // for (const auto& p : A) {
    //     cout << p.first << ": " << p.second << endl;
    // }
}

更简洁的Lambda表达式写法

不需要单独定义cmp函数,直接在sort调用时传入lambda表达式,代码更紧凑:

void sortByValueDesc(map<string, int>& M)
{
    // 直接用map迭代器初始化vector,省去手动循环push_back
    vector<pair<string, int>> sortedVec(M.begin(), M.end());
    
    // 传入lambda实现降序比较
    sort(sortedVec.begin(), sortedVec.end(), 
         [](const pair<string, int>& a, const pair<string, int>& b) {
             return a.second > b.second;
         });
    
    // 处理排序后的结果,比如输出
    // for (const auto& item : sortedVec) {
    //     cout << item.first << ": " << item.second << endl;
    // }
}

关于反向遍历Map的说明

你提到的反向遍历Map,本质是按Key的降序遍历,而非按Value排序。Map本身默认按Key升序存储,反向遍历可通过rbegin()和rend()实现:

// 反向遍历Map(按Key降序输出)
for (auto it = M.rbegin(); it != M.rend(); ++it) {
    cout << it->first << ": " << it->second << endl;
}

注意:这种方式不会改变元素的存储顺序,也不是按Value排序,只是遍历顺序反转。如果需求是按Value降序,还是需要采用将Map转为Vector再排序的方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:56:06