HJ8题解 | #合并表记录#(map使用)

合并表记录

https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201

#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
    long da1;
    int num, da2;
    map<long, int> mp;
    map<long, int>::iterator it;
    string temp;
    cin>>num;
    cin.ignore();
    for(int i=0; i<num; i++)
    {
        getline(cin, temp);
        int loc = temp.find(" ");
        //看题,数字会不只一位,找空格来分割
        da1 = stoi(temp.substr(0, loc), nullptr, 10);
        da2 = stoi(temp.substr(loc+1, (temp.size()-loc-1)), nullptr, 10);
        if(mp.find(da1) == mp.end())
        {
            mp.insert(pair<long, int>(da1, da2));
        }
        else
        {
            mp[da1] = mp[da1] + da2;
        }
    }
    for(it=mp.begin(); it!=mp.end(); it++)
    {
        cout<<it->first<<" "<<it->second<<endl;
    }    
}

考察map使用,注意数字可以很大,所以用查找空格来分割,cin之后会残留\n在缓冲区,用cin.ignore()即可。

全部评论

相关推荐

KPLACE:首先是板面看起来不够,有很多奖,比我厉害。项目要精减,大概详细描述两到三个,要把技术栈写清楚,分点,什么算法,什么外设,怎么优化,不要写一大堆,分点,你写上去的目的,一是让别人知道你做了这个知识点,然后在面试官技术面的时侯,他知道你会这个,那么就会跟你深挖这个,然后就是个人评价改为专业技能
点赞 评论 收藏
分享
2024-12-26 13:00
太原理工大学 Java
会飞的猿:简历没啥大问题啊,感觉是缺少了实习经历。多投投先找个中小厂过渡一下吧
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 22:33
杉川机器人 嵌入式工程师 18.0k*13.0, 年终奖1~9个月
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务