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

C++中如何将统计IP访问次数的map按次数降序输出

C++ 按IP出现次数降序输出解决方案

std::map 默认以键(IP字符串)的字典序排序,无法直接按值(出现次数)调整排序逻辑。你可以保留原有的统计逻辑不变,仅在输出前将统计结果转存到支持自定义排序的std::vector中,排序后再输出即可,修改成本极低。

必要头文件补充

如果你的代码中没有引入以下头文件请先补充:

#include <vector>
#include <algorithm>

修改代码步骤

  1. 原有IP统计逻辑完全不用调整,在统计完成后、输出之前添加如下代码,将std::map的键值对转存到vector并按次数降序排序:
// 把统计结果转存到vector中
std::vector<std::pair<std::string, int>> countVec(stringCount.begin(), stringCount.end());
// 自定义排序规则:按出现次数降序排列
std::sort(countVec.begin(), countVec.end(), [](const std::pair<std::string, int>& a, const std::pair<std::string, int>& b) {
    return a.second > b.second;
});
  1. 将原来遍历stringCount输出的循环,替换为遍历排序后的countVec即可:
for(const auto& pairElement: countVec)
{
    std::cout<<pairElement.first<<" => "<<pairElement.second<<" times "<<std::endl;
    outputFile<<pairElement.first<<" => "<<pairElement.second<<" times \n";
}

可选扩展

如果需要处理出现次数相同的IP排序需求,比如次数相同时按IP字典序升序排列,只需要修改排序的lambda表达式即可:

std::sort(countVec.begin(), countVec.end(), [](const std::pair<std::string, int>& a, const std::pair<std::string, int>& b) {
    // 先按次数降序,次数相同按IP字典序升序
    return a.second != b.second ? a.second > b.second : a.first < b.first;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 01:54:04