如何自定義map排序
sort僅僅支持pair,vector,數(shù)組等排序,不支持對map的排序
所以如果想用sort對map排序的話,只需要把map轉(zhuǎn)換為vector即可:
map<int,int>res;
res[1]=1,res[2]=2,res[3]=3;
vector<pair<int,int>>rest;
for(auto it=res.begin();it!=res.end();it++)
rest.push_back((pair<int,int>(it->first,it->second)));
再輸出vector,即可得到我們想要的結(jié)果
如果想要在map遍歷的時候,可以直接輸出排序的結(jié)果,大不了把原來的map刪掉,再把vector的內(nèi)容重新賦值進去就行了
附上map遍歷的方法
(string的data方法可以返回指向該字符串的第一個字符的字符型指針)
map<string, 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 <<endl;
}
csp第四次第二題--數(shù)字排序
文章來源:http://www.zghlxwxcb.cn/news/detail-704515.html
題解如下,思考map的使用技巧文章來源地址http://www.zghlxwxcb.cn/news/detail-704515.html
#include<map>
#include<iostream>
#include<utility>
#include<vector>
#include<algorithm>
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<b.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<pair<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<rest.size();i++)cout<<rest[i].first<<" "<<rest[i].second<<endl;
return 0;
}
到了這里,關(guān)于【C++】map值自定義key,value排序(含ccfcsp第四次認證第二題演示和map遍歷方法)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!