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()即可。
查看14道真题和解析