第一课 STL入门

A-统计数字

1.题目内容、

给定 $n$ 个数字,统计出现次数最多的。如果有多个数字出现次数都是最多的,从小到大输出。

2.问题思路

可以用一个 map 统计出现过的数字,先用一个迭代器遍历一遍,找出最大值,然后再遍历一遍找出出现次数等于最大值的数。

3.考点

map 的用法

map 的访问方式:map[idx]。

定义方式: map<数据类型,数据类型>。

迭代器:map<数据类型,数据类型>::iterator it=mp.begin()。

访问:it->first 指向 map 的第一个数据类型,it->second 指向第二个。

4.代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<bits/stdc++.h>
using namespace std;

map<int,int> mp;

int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
int x;scanf("%d",&x);mp[x]++;
}
map<int,int>::iterator it=mp.begin();
int mx=0;
int id=0;
for(;it!=mp.end();it++)
{
if(it->second>mx) mx=it->second,id=it->first;
}
it=mp.begin();
for(;it!=mp.end();it++)
{
if(it->second==mx) printf("%d ",it->first);
}
}