题解 | #键值对类型的题#

合并表记录

http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201

键值对类型的题,利用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;
    }
    
}
全部评论

相关推荐

之前听说有的人会把双非直接写成某211,还藏了好几年
还在等面试的卑微求职:可以的,下次直接写C9,然后面试官一问三不知,永久拉黑
点赞 评论 收藏
分享
09-01 10:50
已编辑
东华大学 C++
PDD校招_内推:拼多多意向和开奖一般都比较晚,可能10月11月才出意向
点赞 评论 收藏
分享
09-09 16:12
已编辑
成都理工大学 Java
future0210:学java就是好啊,啥都能转
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务