map是一个很有用的映射工具,底层用红黑树实现,所以也是自动有序的(按照键值key排序)
#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
int main()
{
//map译为映射,常用的STL容器之一
//int数组是定义了一个int到int类型的映射,double类型则是定义int到double的映射
//但数组似乎只能从int映射到其他类型,当我们想要用其他类型进行映射的时候很不方便
//我们也可以采用hash散列来解决冲突,例如PAT1039中采用的方法
//但map也给我们提供了解决方案
//map的功能是可以将任何基本类型(包括STL容器),映射到任何基本类型(同STL)
//map的定义和其他STL容器不同,需要确定映射前类型(键key)和映射后类型(值value)
//for instance: map<typename1,typename2>mp;
//如果是字符串映射到整型,只能用string类而不能用char数组
//map有两种访问方式,迭代器访问和下标访问
//下标访问
map<char,int>mp;
mp['c']=20;
mp['c']=30;//覆盖20
printf("visit by rank: %d\n",mp['c']);
//迭代器访问,it->first是当前映射的键,it->second是当前映射的值
//因为map内部是用红黑树实现的(同set),在建立映射的过程中自动按key排序
map<char,int>mp1;
mp1['m']=20;
mp1['r']=30;
mp1['a']=40;
for(map<char,int>::iterator it=mp1.begin();it!=mp1.end();it++)
printf("visit by iterator: %c %d\n",it->first,it->second);
//find(key)返回键值为key的映射的迭代器,O(logN),N为map中元素数量
map<char,int> mp2;
mp2['a']=1;
mp2['b']=2;
mp2['c']=3;
map<char,int>::iterator it2=mp2.find('b');
printf("it=mp2.find('b'): %c %d\n",it2->first,it2->second);
//erase()有两种用法:删除单个元素,删除指定区间的所有元素
//删除单个元素有两种方法:用mp.erase(it),it是需要删除元素的迭代器,O(1)
map<char,int>::iterator it=mp2.find('b');
mp2.erase(it);
printf("after use erase by it:\n");
for(map<char,int>::iterator it=mp2.begin();it!=mp2.end();it++)
printf("%c %d\n",it->first,it->second);
mp2['b']=2;
//mp.erase(key),key为欲删除的映射的键,O(logN),N为map内元素个数
mp2.erase('b');
printf("restore mp2['b']=2 \nuse erase by key:\n");
for(map<char,int>::iterator it=mp2.begin();it!=mp2.end();it++)
printf("%c %d\n",it->first,it->second);
//删除区间内的所有元素:mp.erase(first,last),同set和vector一样,[first,last)
mp2['b']=2;
printf("restore mp2['b']=2 \nuse erase by erase[]:\n");
it=mp2.find('b');
mp2.erase(it,mp2.end());
for(map<char,int>::iterator it=mp2.begin();it!=mp2.end();it++)
printf("%c %d\n",it->first,it->second);
//size()同样是用来获得map的大小,即映射的对数,O(1)
mp2['b']=2;
mp2['c']=3;
printf("after restore mp2 the size: %d\n",mp2.size());
//clear()用来清空map中所有元素
mp2.clear();
printf("after clear mp2 the size: %d",mp2.size());
return 0;
}