一、关于map
1.本质:提供任意两个数据类型之间的映射(包括STL容器之间的映射)
2.优点:建立两个不同类型数据之间的联系,并可以在内部根据键值(第一个 type 值自动从小到大排序)。
二、使用map
1.定义
前一个数据类型为键的类型,第二个类型为值的类型。如map<string, int>是把 string 类型映射到 int 类型。
map<char , int> mp; //字符型映射到整数型.
map<string , int> mp; //字符数组的映射必须使用 string .
map<set<int> , int> mp;
2.访问
通过下标访问:
#include<stdio.h>
#include<map>
using namespace std;
int main(){
map<char , int> mp;
mp['c'] = 20;
printf("%d",mp['c']);
return 0;
}
通过迭代器访问:
/*定义迭代器 it 之后,可以采用 it->first 访问键,采用 it->second 访问值。*/
#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++){
prinft("%c %d\n",it->first,it->second);
}
}
3.常用函数
3.1 find
/*返回键为特定值的映射的迭代器*/
map<char , int>::iterator it = mp.find('b');
3.2 erase
删除单个元素
// 1. 通过迭代器进行删除
map<char ,int>::iterator it = mp.find('b');
mp.erase(it);
// 2. 通过键进行删除
mp.erase('b');
//以上两种方法均是删除键为 b 的元素。
删除一个区间内的元素
map<char,int>::iterator it = mp.find('b');
mp.erase(it,mp.end());
//删除从 it 到最后的所有映射,注意 erase 函数的两个从参数类型都是迭代器。
3.3 size
int size = mp.size();
//返回映射的对数
3.4 clear
mp.clear();
//清空所有的映射
更多类型的使用方法见专栏。