map按值排序–获取出现次数最多的前n个字符串
- map中的元素是key-value队,关键字起索引作用,值表示索引相关的数据
- map的底层事项时基于红黑树来是想的,因此map内部元素排列是有序的–中序遍历即为有序
- map的查找、删除、增加等一系列的操作时间复杂度稳定,都为O(logN)
- 查找、删除增加等平均时间复杂度较慢,与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;
stmp.clear();
stmp.str("");
}
for (auto& x : simap)
{
cout << x.first << " ==> " << x.second << endl;
}
vector<pair<string,int>>v;
for(auto &x:simap){
v.push_back(x);
}
sort(v.begin(),v.end(),cmp);
cout<<"出现次数最多的10个ip地址"<<endl;
for(int i=0;i<10;i++){
cout<<v[i].first<<"=>"<<v[i].second<<endl;
}
return 0;
}