映射操作(查找大多数发生元素) [英] map operations(find most occurence element)

查看:198
本文介绍了映射操作(查找大多数发生元素)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是代码

#include <iostream>
#include <map>
using namespace std;
int main(){
map<int ,int>a;
    map<int,int>::iterator it;
    int b[]={2,4,3,5,2,6,6,3,6,4};
     for (int i=0;i<(sizeof(b)/sizeof(b[0]));i++){
         ++a[b[i]];
     }
    // for (it=a.begin();it!=a.end();it++){
        // cout<<(*it).first<<" =>"<<(*it).second<<"\n";
     //}
     int max=a.begin()->second;
     for (it=a.begin();it!=a.end();it++){
         if ((*it).second>max){
             max=(*it).second;
         }
     }
     for (it!=a.begin();it!=a.end();it++){
         if ((*it).second==max){
             cout<<(*it).first<<"\n";
         }
     }




      return 0;
}

我想要的是根据我想要的每个键的发生次数它打印元素在这种情况下最常出现6但它不显示结果是什么是错误?

what i am trying is following according to number of occurence of each keys i want it print element which occurs most often in this case 6 but it does not show me result what is mistake?

推荐答案

打错你的第二个循环。 This:

You have a typo in your second loop. This:

for (it!=a.begin();it!=a.end();it++){

应为:

for (it=a.begin();it!=a.end();it++){

顺便说一下,(* it).first 可以更惯用的写成 it-> c $ c>。箭头运算符( - > )是取消引用( * )和成员访问$ c>。)运算符。

By the way, (*it).first can be more idiomatically written as it->first. The arrow operator (->) is a combination of the dereference (*) and member access (.) operators.

这篇关于映射操作(查找大多数发生元素)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆