文章目录
STL关联容器 map
映射容器(map):一对多映射,基于关键字快速查找,不允许重复值
map 的特点:每次放入两个数据 <key,value>,key 有序且不重复
1. 操作
1.1 初始化和查找
初始化map词典并访问
#include <iostream>
#include <map>
using namespace std;
int main(){
// 映射dict目录/词典
map<string,string> dict = {
// key value
{
"Apple","苹果"},
{
"Orange","橘子"},
{
"Banana","香蕉"} // 重复key忽略
};
string s;
cin >> s;
// if(dict.count(s) == 1)
if(dict.find(s) != dict.end()){
cout << dict[s] << endl;
}else{
cout << s << "不存在" << endl;
}
}
结果为:
Apple
苹果
1.2 迭代器遍历
将 map 词典遍历打印
#include <iostream>
#include <map>
using namespace std;
int main(){
// 映射dict目录/词典
map<string,string> dict = {
// key value
{
"Apple","苹果"},
{
"Orange","橘子"},
{
"Banana","香蕉"}
};
map<string,string>::iterator it = dict.begin();
while(it != dict.end()){
cout << it->first << "," << it->second << endl;
++it;
}
}
其中 it->first 指的是 key 而 it->second 指的是 value
结果为:
Apple,苹果
Banana,香蕉
Orange,橘子
1.3 添加、修改和删除
对原有的 map 数据进行添加、修改和删除
#include <iostream>
#include <map>
using namespace std;
int main(){
// 映射dict目录/词典
map<string,string> dict = {
// key value
{
"Apple","苹果"},
{
"Orange","橘子"},
{
"Banana","香蕉"},
{
"苹果","Apple"},
{
"橘子","Orange"},
{
"香蕉","Banana"} // 重复key忽略
};
// 添加新的数据
dict["Car"]="汽车";
dict.insert(pair<string,string>("One","一"));
dict.insert(make_pair("大","Big"));
dict.insert({
"二","Two"}); // C++11
// 修改数据
dict["Car"]="小汽车";
// 删除
dict.erase("Apple");
// 打印一下
map<string,string>::iterator it = dict.begin();
while(it != dict.end()){
cout << it->first << "," << it->second << endl;
++it;
}
}
结果为:
Banana,香蕉
Car,小汽车
One,一
Orange,橘子
二,Two
大,Big
橘子,Orange
苹果,Apple
香蕉,Banana
2. 相关练习
2.1 力扣面试题 16.02:单词频率
题目:
设计一个方法,找出任意指定单词在一本书中的出现频率。
你的实现应该支持如下操作:
WordsFrequency(book)构造函数,参数为字符串数组构成的一本书
get(word)查询指定单词在书中出现的频率
解题:
- 把数据依次都放在 map 中,如果有则记为1,如果没有数量+1进行计数
- 在 map 中查找的数据,没找到返回0,找到返回 value
class WordsFrequency {
public:
WordsFrequency(vector<string>& book) {
for(auto word:book