PAT刷题——map以及字符串翻转

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牛批,这种有序的问题可以很方便地解决了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值