sort仅仅支持pair,vector,数组等排序,不支持对map的排序
所以如果想用sort对map排序的话,只需要把map转换为vector即可:
- map<int,int>res;
- res[1]=1,res[2]=2,res[3]=3;
- vector
int,int>>rest; - for(auto it=res.begin();it!=res.end();it++)
- rest.push_back((pair<int,int>(it->first,it->second)));
再输出vector,即可得到我们想要的结果
如果想要在map遍历的时候,可以直接输出排序的结果,大不了把原来的map删掉,再把vector的内容重新赋值进去就行了
附上map遍历的方法
(string的data方法可以返回指向该字符串的第一个字符的字符型指针)
- map
int>::iterator it; - for (it = m2.begin(); it != m2.end(); it++) {
- string s = it->first;
- printf("%s %d\n", s.data(), it->second);
- }
- for(auto it : map1){
- cout << it.first <<" "<< it.second <
- }
csp第四次第二题--数字排序


题解如下,思考map的使用技巧
- #include
- #include
- #include
- #include
- #include
- using namespace std;
- int n;
- map<int,int>res;
- bool cmp(pair<int,int>a,pair<int,int>b)
- {
- if(a.second!=b.second)return a.second>b.second;
- else
- return a.first
- }
- int main()
- {
- cin>>n;
- for(int i=1;i<=n;i++)
- {
- int x;
- cin>>x;
- if(!res.count(x))res[x]=1;
- else res[x]++;
- }
- vector
int,int>>rest; - for(auto it=res.begin();it!=res.end();it++)
- rest.push_back((pair<int,int>(it->first,it->second)));
- sort(rest.begin(),rest.end(),cmp);
- for(int i=0;i
size();i++)cout<" "< - return 0;
- }
-
相关阅读:
element-ui配置
deepstream 检测结果截图
一点一点学习C++之笔记003
用时半个月,终于把2020年各大公司的Java面试题精选整理成文档了
Vue3 按需引入 Element Plus
Java 8实战(八)- 数值流与构建流
【对象存储】SpringBoot集成华为云OBS对象存储
小白也可以开发闲鱼自动化发布工具!!!
C++ 字符串
【云原生 | Kubernetes 实战】07、Pod 高级实战:Pod 生命周期、启动钩子、停止钩子
-
原文地址:https://blog.csdn.net/m0_63222058/article/details/132788409