1. map定义
1. 定义一个map : map<type1,type2>mp ,
type1是映射前的类型(键key),typename2是映射后的类型
(值 value),mp为映射的名字。
2.map表达映射关系 , 其实数组也是一种映射
例如 int a[100] 定义了int 到 int 的映射关系
a[5]=10 ,将 5 与10 建立了 5 到映射到10 关系
但是 map 可以映射 任何基本类型 (包括STL 容器)
map<string ,int >mp ; // 将string 映射为 int
map<string ,string >mp; // 将string 映射为 string
map<set<int >,string >mp; // 将set容器 映射到string
2.map的访问
1.通过下标访问
#include<iostream>
#include<cstdio>
#include<algorithm>
#include <map> // 使用map 的必要头文件
using namespace std;
int main()
{
map<char,int>mp;
mp['c']=100;
mp['d']=124;
cout<<mp['c']<<endl;
return 0;
}
// 输出结果为 100
2.通过迭代器访问 (重中之重)
map<type1,type2>::iterator it; //正向迭代,从第一个键元素开始访问
type1和type2就是定义map时填写的类型,这样就得到了迭代器it
通过 使用it->first来访问键,用it->second来访问值。// map<键,值>mp
#include<iostream>
#include<cstdio>
#include<algorithm>
#include <map>
using namespace std;
int main()
{
map<int ,string>mm;
mm[1]="abc";
mm[2]="acf";
map<int ,string >::iterator it1;
for(it1=mm.begin();it1!=mm.end();it1++)
{
cout<<it1->first<<" "<<it1->second<<endl;
}
return 0;
}
/*输出结果:
1 abc
2 acf
*/
3.反向迭代器 (一般不用)
map<type1,type2>:: reverse_iterator it; // 反向迭代,从最后的键 访问
it->rbegin() , it->rend();
#include<iostream>
#include<cstdio>
#include<algorithm>
#include <map>
using namespace std;
int main()
{
map<int ,string>mm;
mm[1]="abc";
mm[2]="acf";
map<int ,string >::reverse_iterator it;
for(it=mm.rbegin();it!=mm.rend();it++)
{
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
/*输出结果:
2 acf
1 abc
*/
3.map 常用函数
begin() 返回指向map头部的迭代器
end() 返回指向map末尾的迭代器
clear() 删除所有元素
empty() 判断map是否为空,如果map为空则返回true
size() 返回map中元素的个数
find() 查找一个元素的键值, 返回该元素的迭代器
//rbegin() 返回一个指向map尾部的逆向迭代器
//rend() 返回一个指向map头部的逆向迭代器
举例 :find()的使用;
#include<stdio.h>
#include<cstdio>
#include<iostream>
#include<map>
#include<algorithm>
using namespace std;
int main(){
map<char,int> mp;
mp['c']=20;
mp['a']=40;
mp['r']=60;
map<char,int>::iterator it=mp.find('a');
printf("%c %d\n",it->first,it->second);
return 0;
}
/*输出结果:
a 40
*/
4.map的特点及作用(处理什么问题)
特点: map会以键(key)从小到大的顺序自动排序,
这是由于map内部是使用红黑树实现的(set也是).
map<string ,int >mp; 键为string型, map内数据顺序 会按 字典序 从小到大
map<int ,int >mp1; 键为int 型, map内数据顺序 会按 整数值 从小到大
解决问题:
(1)需要建立字符(串)与整数之间映射的题目
(2)判断大整数(比如 几千位的数)或者其他类型的数据是否存在的题目,
可以把map当bool数组使用(哈希表)
(3)字符串和字符串的映射
(4)建立较大整数与较大整数的联系 map<long long ,long long >mp;
显然无法用数组开到 long long 的 空间大小
5 思维拓展(map的嵌套使用)
下面例子的核心 : 将外层 的 it1->second 变成内层 迭代器的 开始
可参考这道题目: hdu 1263
map<string,map<string ,int > >mp; // 在map 中嵌套 一个map容器
map<string,map<string ,int> >::iterator it1; // 外层迭代器
for(it1=mp.begin();it1!=mp.end();it1++) // 遍历方式
{
cout<<it1->first<<endl;
map<string ,int >::iterator it2; // 内层迭代器
for(it2=it1->second.begin();it2!=it1->second.end();it2++)
{
cout<<it2->first<<" "<<it2->second<<endl;
}
}