C++中如何将统计IP访问次数的map按次数降序输出
C++ 按IP出现次数降序输出解决方案
std::map 默认以键(IP字符串)的字典序排序,无法直接按值(出现次数)调整排序逻辑。你可以保留原有的统计逻辑不变,仅在输出前将统计结果转存到支持自定义排序的std::vector中,排序后再输出即可,修改成本极低。
必要头文件补充
如果你的代码中没有引入以下头文件请先补充:
#include <vector> #include <algorithm>
修改代码步骤
- 原有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; });
- 将原来遍历
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
相关产品推荐
相关产品推荐

