前言:
在这个笔记中,我把大多数代码都加了注释,我的一些想法和注解用蓝色字体标记了出来,重点和需要关注的地方用红色字体标记了出来。
在这一篇文章中,我们主要介绍map的用法和应用
1.1 map的用法
与multimap的区别在于:
1、不能有重复的元素。
2、可以使用[],下标为关键字,返回值为first和关键字相同的元素的second。(中括号里面放下标,和python里面的字典感觉差不多)
3、插入元素可能失败。
(与set和multiset的差别差不多)
1.2 map的应用
样例:
1 #include
2 #include
样例
老样子,老师总是在讲程序的时候说重点,这个时候就需要我来整理一下了。
mp["Jack"] = 60;
这里是将mp里“jack”对应的second修改为了60。
st.name = "Jack";
st.score = 99;
pair p =
mp.insert(make_pair(st.name,st.score));
这里和之前set时一样,使用了一个pair变量p来接受插入的结果,样例里的结果是failed,pair变量的first指向了已有的jack,second是false。如果改一下使之插入♂成功的话,会发现first指向刚刚插入的值的位置,second为true。
mp["Harry"] = 78;
表面上看起来和前面mp[“jack”]是一样的,实际上这里不存在一个叫Harry的键,这句代码的作用是插入一个first为“Harry”,second为78的变量。
例题:单词词频统计程序
输入大量单词,每个单词,一行,不超过20字符,没有空格。按出现次数从多到少输出这些单词以及出现次数。出现次数相同的,字典序靠前的在前面。(这种时候排序+查找就会显得非常低效,每插入一个就要全部重新排序一次,岂不麻烦,除非知道只有哪些单词,那样就比较快了)
1 /*
2 例题:单词词频统计程序
3 输入大量单词,每个单词,一行,不超过20字符,没有空格。
4 按出现次数从多到少输出这些单词以及出现次数。
5 出现次数相同的,字典序靠前的在前面。
6
7 输入样例:
8 this
9 is
10 ok
11 this
12 plus
13 that
14 is
15 plus
16 plus
17 -1
18 输出样例:
19 plus 3
20 is 2
21 this 2
22 ok 1
23 that 1
24 */
25 #include
26 #include<set>
27 #include
程序
在这里我们能发现,mp的默认值是0,这样就可以直接++mp[s]而不必要初始化一遍,只不过不知道如果map的键值对定义成其他样子的话,默认值会是多少了。
后记:
摸鱼,摸不得也,要是本科生想干啥干啥就好了(哈哈哈做梦),那样我就天天来学习各种编程相关知识了(也可能摸鱼)。总之感谢读到这里,希望能对你有帮助吧。