map按值排序--输出出现次数最多的字符串

map按值排序–获取出现次数最多的前n个字符串

  1. map中的元素是key-value队,关键字起索引作用,值表示索引相关的数据
  2. map的底层事项时基于红黑树来是想的,因此map内部元素排列是有序的–中序遍历即为有序
  3. map的查找、删除、增加等一系列的操作时间复杂度稳定,都为O(logN)
  4. 查找、删除增加等平均时间复杂度较慢,与n相关
#include <iostream>
#include <vector>
#include <random>
#include <algorithm>
#include <sstream>
#include <map>
using  namespace std;
bool cmp(const pair<string,int>&a,const pair<string,int>&b){
    return a.second>b.second;//从大到小
}
int main()	   //
{
    std::map<std::string, int > simap;
    std::string ip;
    std::stringstream stmp;
    for (int i = 0; i < 100000; ++i)
    {
        stmp <<127 << "." << 45 << "." <<23 << "." << rand() % 256;
        ip = stmp.str();
        simap[ip] += 1;
        //清楚stemp的值
        stmp.clear();
        //将缓冲区置为0
        stmp.str("");
    }
    for (auto& x : simap)
    {
        cout << x.first << " ==> " << x.second << endl;

    }
    //因为map的第一个是通过字典序来进行,所以这里要放入到vector当中队第二个--出现次数继续进行比较
    vector<pair<string,int>>v;
    for(auto &x:simap){
        v.push_back(x);
    }
    //调用系统的快排--同时重写--sort自带的从小到大的排序比较函数
    sort(v.begin(),v.end(),cmp);
    //获取出现次数最多的10个值
    cout<<"出现次数最多的10个ip地址"<<endl;
    for(int i=0;i<10;i++){
        cout<<v[i].first<<"=>"<<v[i].second<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HANWEN KE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值