map
map默认使用升序排列,要降序输出可以使用反向迭代器。
unordered_map不排序,在大模拟题map超时时使用。
1002 应用map反向迭代
https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000
#include <bits/stdc++.h>
using namespace std;
map<int,double>mp;
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
int k,e;
double c;
cin>>k;
while(k--){
cin>>e>>c;
mp[e]+=c;
if(mp[e]==0)mp.erase(e);
}
cin>>k;
while(k--){
cin>>e>>c;
mp[e]+=c;
if(mp[e]==0)mp.erase(e);
}
printf("%d",mp.size());
for(auto it=mp.rbegin();it!=mp.rend();it++){
printf(" %d %.1f",it->first,it->second);
}
return 0;
}
map默认按key的升序排列,为了得到从高次到低次的顺序,使用反向迭代。
注意auto关键字,
当使用范围for循环时,使用m.first,m.second
当使用迭代器时,使用it->first,it->second
此外此题还有一个坑点,就是系数为0时应该去掉此值,或在map中直接删除,或在输出时做出判断。map中直接删除使用erase方法
字符串翻转
原地翻转(直接在原字符串上翻转)
reverse(s.begin(),s.end());
reverse的参数是迭代器,别写多了Python就把string直接作为参数传入。
翻转并赋值为另外一个string
sr.assign(s.rbegin(),s.rend());
使用反向迭代器
1001 使用反转字符串
#include <bits/stdc++.h>
using namespace std;
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin) ;
#endif
int a,b;
cin>>a>>b;
int sum=a+b;
int absSum=abs(sum);
string s=to_string(absSum);
string sr;
sr.assign(s.rbegin(),s.rend());
string ans;
for(int i=0;i<sr.size();i++){
ans+=sr[i];
if(i!=0&&i%3==2&&i!=sr.size()-1)ans+=",";
}
reverse(ans.begin(),ans.end());
if(sum<0)cout<<"-";
cout<<ans;
return 0;
}
总结
今天熟悉了反向迭代器的作用,尤其是map降序输出着实解决了很多疑惑带来了很大便利,之前都考虑到只能升序就不能普适,但看到了可以反向迭代简直醍醐灌顶、耳目一新。
map牛批,这种有序的问题可以很方便地解决了。