相同索引的数值进行求和运算,输出按照key值升序进行输出

数据表记录包含表索引和数值(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。

img


#include <iostream>
#include <map>
using namespace std;
int main()
{
    map<int, int> iimap;
    int key, value, num;
    cin >> num;
    while (num-- && cin >> key >> value)
        iimap[key] += value; //不存在的时候默认是0,存在则累加
    for (auto beg = iimap.begin(); beg != iimap.end(); ++beg)
        cout << beg->first << " " << beg->second << endl;
    return 0;        
}