参考书籍:
《挑战程序设计竞赛》巫泽俊 主译
《算法竞赛入门经典》刘汝佳 著
一、映射map是什么?
集合与映射是两个常用的容器。映射map是一种“关联容器”,就是从键key到值value的映射,相信熟悉json的程序员们一定对键值对不陌生。
可以把它想象成两个被关联了的数组,两个数组中下标相同的值一一对应。
map常用于一对一的存储数据,类似于Python中的字典。
它的特点是增加和删除节点对迭代器的影响很小,除了那个操作节点,对其他的节点都没有什么影响。
下面通过一个程序来熟悉map的各种基本用法:
二、map使用
这里列举最常用的一些功能和方法。通过一个程序了解所有常用方法。
#include<iostream>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
map<string,int> cnt;//单词映射到单词出现次数
int main()
{
//插入元素两种方式
cnt.insert(make_pair("one",1));
cnt.insert(make_pair("two",2));
cnt["hundred"]=100;
//输出方法1:通过键得到值
cout<<cnt["two"]<<endl;//2
//创建迭代器
map<string,int>::iterator ite;//创建迭代器
ite=cnt.find("one");
//输出方法2:通过迭代器的第二项得到值
cout<<ite->second<<endl;//1
ite=cnt.find("hundred");
cout<<ite->second<<endl;//100
//修改键对应值为200
cnt["hundred"]=200;
for(ite=cnt.begin();ite!=cnt.end();ite++){//利用迭代器遍历映射
cout<<ite->first<<" "<<ite->second<<endl;
/*循环运行结果
hundred 200
one 1
two 2*/
}
//删除元素
cnt.erase("hundred");
for(ite=cnt.begin();ite!=cnt.end();ite++){//利用迭代器遍历映射
cout<<ite->first<<" "<<ite->second<<endl;
/*循环运行结果
one 1
two 2*/
}
return 0;
}