题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <iostream>
#include<string>
#include<vector>
#include<map>
using namespace std;
//数据表记录包含表索引index和数值value(int范围的正整数),
//请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。
/*提示:
0 <= index <= 11111111
1 <= value <= 100000
*/
int main()
{
int a;
cin >> a;
map<int, int> m;
int i=-1, j=-1;
while (a--)
{
cin >> i;
cin >> j;
map<int, int>::iterator it = m.begin();
for (; it != m.end(); it++)
{
if (it->first == i) //如果输入的key值与map容器里有一样的 那就进行value值的相加
{
m[i] = it->second + j;
break;
}
}
//怎么才能判断找到了 m[i] 不等于他原来的数了 则表示已经加了 不需要在写入 map
// 或者判断it遍历没有遍历到最后就break退出;
if (it != m.end())
{
continue;
}
m[i] = j;
}
for (map<int,int>::iterator it = m.begin(); it != m.end(); it++)
{
cout <<it->first <<" "<<it->second << endl;
}
system("pause");
return 0;
}