题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
先读入键值对的个数n,再循环读入n个键值对,用map存储,如果能在map中找到数据则累加值
#include <iostream>
#include <map>
using namespace std;
int main()
{
int n;
int index,value;
map<int,int> m_map;
//读入键值对的个数;
scanf("%d", &n);
//循环读入;
for(int i=0;i<n;i++)
{
scanf("%d%d", &index, &value);
map<int,int>::iterator iter = m_map.find(index);
if(iter != m_map.end())
{
iter->second += value;
}
else
{
m_map[index] = value;
}
}
//输出;
for(auto& o: m_map)
{
printf("%d %d\n", o.first, o.second);
}
return 0;
}
查看4道真题和解析