交易清单(京东2016实习生真题)

本文介绍了一种使用C++标准库中的map容器来处理数据统计问题的方法。通过示例代码展示了如何利用map进行键值对的增删查改操作,并实现了按特定条件输出的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此题用map,直接码:

#include<cstdio>
#include<cstring>
#include<map>
#include<algorithm>
using namespace std;

int main(){

    int n,s;
    char c;
    int x,y;
    // 默认按键升序升序排,这样写降序排
    map<int,int,greater<int> > smap,bmap;
    while(scanf("%d %d",&n,&s)!=EOF)
    {
        // map 删除所有元素
        smap.clear();
        bmap.clear();
        // map 是否为空 返回true or false
        //smap.empty() ? printf("true\n") : printf("false\n");
        for(int i=0 ;i<n ;i++)
        {
            getchar();
            scanf("%c %d %d",&c,&x,&y);
            if(c == 'S')
                smap[x] += y;
            if(c == 'B')
                bmap[x] += y;
        }

        //printf("smap 中元素的个数:%d\n",smap.size());

        //返回一个迭代器对象
        map<int,int,greater<int> >::iterator it;
        //查找一个指定元素
        //find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。
        //it = smap.find(12);
        // 如果要删除的话
        //smap.erase(it);

        int scount = smap.size() > s ? s : smap.size();
        int bcount = bmap.size() > s ? s : bmap.size();

        for(it = smap.begin() ; it != smap.end(); it++)
        {
            printf("S %d %d\n",it->first,it->second);
            scount--;
            if(scount == 0)
                break;
        }

        for(it = bmap.begin() ; it != bmap.end(); it++)
        {
            printf("B %d %d\n",it->first,it->second);
            bcount--;
            if(bcount == 0)
                break;
        }



    }
}

重新学习下map的用法
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值