[洛谷] P1097 统计数字

题目链接

AC代码

 1 #include <stdio.h>
 2 #include <map>
 3 #include <set>
 4 using namespace std;
 5 map<int,int> ct_number;
 6 int main()
 7 {
 8     int n;
 9     scanf("%d",&n);
10     for(int i = 0;i < n;i++)
11     {
12         int tmp;
13         scanf("%d",&tmp);
14         ct_number[tmp]++;
15     }
16     for(map<int,int>::iterator it = ct_number.begin();it != ct_number.end();it++)
17     {
18         printf("%d %d\n",it->first,it->second);
19     }
20     return 0;
21 } 
View Code

思路:注意map用法

如int,和double数组本质是建立了index为整数到一个int或double的映射 int->int,int->double.

当我们需要建立其他映射,如记录书还剩多少本,书名->int,此时需要映射string->int。此时可以使用map

1.可以将任何基本类型映射到任何基本类型。

2.map会以键的大小自动排序(若char->int,键为b,c,a,他会自动排序成a,b,c)

3.map键与值唯一对应,类似数组。若要键对应多个值,只能用multimap。

 

反思:1.map内部结构是红黑树,了解一下红黑树

2.若不用map应该怎么做

 

posted @ 2020-04-25 16:26  Ponytai1  阅读(203)  评论(0编辑  收藏  举报