牛客网 小白鼠排队 -- 【结构体】【MAP】

输入描述:

多案例输入,每个案例的输入第一行为一个整数N,表示小白鼠的数目。
下面有N行,每行是一只白鼠的信息。第一个为不大于100的正整数,表示白鼠的重量,;第二个为字符串,表示白鼠的帽子颜色,字符串长度不超过10个字符。

注意:白鼠的重量各不相同。

输出描述:

每个案例按照白鼠的重量从大到小的顺序输出白鼠的帽子颜色。
示例1

输入

复制
3
30 red
50 blue
40 green

输出

复制
blue
green
red

经验总结

  1. 逆序迭代器rbegin()、rend()
 map<int, string> mp;
 map<int,string>::reverse_iterator it;//没有这句话不能使用逆序迭代器
  1. 只有deque、vector、string是可以使用SORT的,而MAP不允许,可以使用sort进行结构体排序;
bool cmp(mouse a,mouse b){
    return a.weight>b.weight;
}
sort(s, s + n, cmp);

AC代码1

//使用MAP和逆序来算的
#include <iostream>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
int main(){
    int t;
    map<int, string> mp;
    map<int,string>::reverse_iterator it;
    while (cin >> t)
    {
        for(int i = 0;i < t;i++){
            int j = 0;
            cin >> j >> mp[j];
        }

        for(auto  it = mp.rbegin();it != mp.rend();it++){
            cout << it->second<<endl;
        }
    }
    return 0;
}

AC代码2

//利用结构体进行计算
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

struct Mouse{
    int weight;
    string color;
}s[100];
bool cmp(Mouse a, Mouse b){
    return a.weight > b.weight;
}
int main(){
    int n;
    while(cin>>n){
        for(int i = 0; i < n; i++){
            cin>>s[i].weight>>s[i].color;
        }
        sort(s, s + n, cmp);
        for(int i = 0; i < n; i++){
            cout<<s[i].color<<endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值