键值对类型的题,利用map键不重复的性质

首先考虑到键不会重复,其次map键具有自动排序的功能,最后可以用迭代器iterator来遍历就好了

#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<int ,int>m;
    int n;
    cin>>n;
    int index,value;
    for(int i=0;i<n;i++)
    {
        cin>>index>>value;
        
        if(m.find(index)!=m.end())//找到某个键对应的位置,与上次已存在的值进行相加
        {
            m[index]+=value;
        }
        else
        {
            m[index]=value;//没有找到某个键对应的位置,直接对相应位置进行赋值就好了,与vector类似
        }
        
    }
    map<int, int>::iterator it;
    for(it=m.begin();it!=m.end();it++)//迭代器遍历就好了
    {
        cout<<it->first<<' '<<it->second<<endl;
    }
    
}