map可以将 任何基本类型 映射 到 任何基本类型
1. map 的定义
map<typename1, typename2> mp;
typename1 --- 映射前类型; typename2 --- 映射后类型
2. map 容器内元素的访问
(1)通过 下标 访问
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char, int> mp;
mp['c'] = 20;
mp['c'] = 30;
printf("%d\n", mp['c']);
return 0;
}
(2)通过 迭代器 访问
map<typename1, typename2>::iterator it;
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char, int> mp;
mp['m'] = 20;
mp['r'] = 30;
mp['a'] = 40;
for(map<char, int>::iterator it = mp.begin(); it != mp.end(); it++){
printf("%c %d\n", it->first, it->second);
}
return 0;
}
3. map 常用函数实例解析
(1)find()
find(key) 返回键值为 key 的映射的迭代器
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char, int> mp;
mp['a'] = 1;
mp['b'] = 2;
mp['c'] = 3;
map<char, int>::iterator it = mp.find('b');
printf("%c %d\n", it->first, it->second);
return 0;
}
(2)erase()
① 删除单个元素
mp.erase(it),it 为需要删除元素 的迭代器
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char, int> mp;
mp['a'] = 1;
mp['b'] = 2;
mp['c'] = 3;
map<char, int>::iterator it = mp.find('b');
mp.erase(it);
for(map<char, int>::iterator it = mp.begin(); it!= mp.end(); it++){
printf("%c %d\n", it->first, it->second);
}
return 0;
}
mp.erase(key),key 为欲删除的映射的键
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char, int> mp;
mp['a'] = 1;
mp['b'] = 2;
mp['c'] = 3;
mp.erase('b');
for(map<char, int>::iterator it = mp.begin(); it != mp.end(); it++){
printf("%c %d\n", it->first, it->second);
}
return 0;
}
② 删除一个区间内的所有元素
mp.erase(first, last),first——删除区间的起始迭代器,last——需要删除区间的末尾迭代器的下一个迭代器
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char, int> mp;
mp['a'] = 1;
mp['b'] = 2;
mp['c'] = 3;
map<char, int>::iterator it = mp.find('b');
mp.erase(it, mp.end());
for(map<char, int>::iterator it = mp.begin(); it != mp.end(); it++){
printf("%c %d\n", it->first, it->second);
}
return 0;
}
(3)size()
获取 map 中映射的对数
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char, int> mp;
mp['a'] = 10;
mp['b'] = 20;
mp['c'] = 30;
printf("%d\n", mp.size());
return 0;
}
(4)clear()
清空 map 中的所有元素
#include <stdio.h>
#include <map>
using namespace std;
int main(){
map<char, int> mp;
mp['a'] = 1;
mp['b'] = 2;
mp.clear();
printf("%d\n", mp.size());
return 0;
}
4. map 的常见用途
- 建立字符(或字符串)与整数之间的映射
- 判断 大整数 或 其他类型数据 是否存在
- 字符串和字符串的映射
——摘抄自《算法笔记》