目录
前言:
在这个笔记中,我把大多数代码都加了注释,我的一些想法和注解用蓝色字体标记了出来,重点和需要关注的地方用红色字体标记了出来。
在这一篇文章中,我们主要介绍map的用法和应用
正文
1.1 map的用法
与multimap的区别在于:
1、不能有重复的元素。
2、可以使用[],下标为关键字,返回值为first和关键字相同的元素的second。(中括号里面放下标,和python里面的字典感觉差不多)
3、插入元素可能失败。
(与set和multiset的差别差不多)
1.2 map的应用
样例:
#include<iostream>
#include<map>
#include<string>
using namespace std;
struct Student
{
string name;
int score;
};
Student students[5] =
{
{"Jack",89},
{"Tom",74},
{"Cindy",87},
{"Alysa",87},
{"Micheal",98}
};
typedef map<string,int>MP;
int main(int argc, char const *argv[])
{
MP mp;
for (int i = 0; i < 5; i++)
{
mp.insert(make_pair(students[i].name,students[i].score));
}
cout<<mp["Jack"]<<endl;//输出:89
mp["Jack"] = 60;//修改名为"Jack"的元素的second
for (MP::iterator i = mp.begin(); i != mp.end(); i++)
{
cout<<"("<<i->first<<","<<i->second<<")";
}//输出:(Alysa,87)(Cindy,87)(Jack,60)(Micheal,98)(Tom,74)
cout<<endl;
Student st;
st.name = "Jack";
st.score = 99;
pair<MP::iterator,bool> p =
mp.insert(make_pair(st.name,st.score));
if (p.second)
{
cout<<"("<<p.first->first<<","<<p.first->second<<") inserted"<<endl;
}
else
{
cout<<"insertion failed"<<endl;
}//输出:insertion failed
mp["Harry"] = 78;//插入一个元素,其first为"Harry",然后将其second改为78
MP::iterator q = mp.find("Harry");
cout<<"("<<q->first<<","<<q->second<<")"<<endl;
//输出:(Harry,78)
return 0;
}
老样子,老师总是在讲程序的时候说重点,这个时候就需要我来整理一下了。
mp["Jack"] = 60;
这里是将mp里“jack”对应的second修改为了60。
st.name = "Jack";
st.score = 99;
pair<MP::iterator,bool> 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字符,没有空格。按出现次数从多到少输出这些单词以及出现次数。出现次数相同的,字典序靠前的在前面。(这种时候排序+查找就会显得非常低效,每插入一个就要全部重新排序一次,岂不麻烦,除非知道只有哪些单词,那样就比较快了)
/*
例题:单词词频统计程序
输入大量单词,每个单词,一行,不超过20字符,没有空格。
按出现次数从多到少输出这些单词以及出现次数。
出现次数相同的,字典序靠前的在前面。
输入样例:
this
is
ok
this
plus
that
is
plus
plus
-1
输出样例:
plus 3
is 2
this 2
ok 1
that 1
*/
#include<iostream>
#include<set>
#include<map>
#include<string>
using namespace std;
struct Word
{
int times;
string wd;
};
struct Rule
{
bool operator()(const Word &w1, const Word &w2)const
{
if(w1.times != w2.times)
return w1.times > w2.times;
else
return w1.wd < w2.wd;
}
};
int main(int argc, char const *argv[])
{
string s;
set<Word,Rule> st;
map<string,int> mp;
while(cin>>s&&s!="-1")//为了方便我小改了一下
++mp[s];//建立之后second默认是0,这里就是对s对应的次数+=1了
for (map<string,int>::iterator i = mp.begin(); i != mp.end(); i++)
{
Word tmp;
tmp.wd = i->first;
tmp.times = i->second;
st.insert(tmp);
}//这里我们先用map来记录word和次数,记录之后再放到set里面排序并输出
for (set<Word,Rule>::iterator i = st.begin(); i != st.end(); i++)
{
cout<<i->wd<<" "<<i->times<<endl;
}
return 0;
}
在这里我们能发现,mp的默认值是0,这样就可以直接++mp[s]而不必要初始化一遍,只不过不知道如果map的键值对定义成其他样子的话,默认值会是多少了。
后记:
摸鱼,摸不得也,要是本科生想干啥干啥就好了(哈哈哈做梦),那样我就天天来学习各种编程相关知识了(也可能摸鱼)。总之感谢读到这里,希望能对你有帮助吧。