定义
map为映射
可以将任何基本类型(包括STL容器)映射到任何基本类型(包括STL容器),也可以建立string到int的类型
map<typename1,typename2> mp;
map容器内元素的访问
通过下标访问
map中键值是唯一的
map以键从小到大自动排序
it->first来访问键,it->second来访问值
通过迭代器访问
常用函数
find()
find(key)访问键为key的映射迭代器,时间复杂度O(logN),N为map中map中的个数
#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
map<char,int> mp;
int main(){
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);
}
#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
map<pair<int,int>,int> mp;
int main(){
for(int i=1;i<=10;i++){
mp[make_pair(i,i)]=i;
}
map<pair<int,int>,int>::iterator it=mp.find(make_pair(5,5));
cout<<it->first.first<<" "<<it->first.second<<" "<<it->second<<endl;
}
#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
struct node{
int x,y;
bool operator<(const node&a) const{
if(x!=a.x)
return x>a.x;
else return y>a.y;
}
};
map<node,int> mp;
node p;
int main(){
for(int i=1;i<=10;i++){
p.x=i*i;p.y=i*i*i;
mp[p]=i;
}
map<node,int>::iterator it;
for(it=mp.begin();it!=mp.end();it++){
cout<<it->first.x<<" "<<it->first.y<<" "<<it->second<<endl;
}
p.x=25;p.y=125;
it=mp.find(p);
cout<<it->first.x<<" "<<it->first.y<<" "<<it->second<<endl;
}
erase()
erase()删除单个元素,删除一个区间内的所有元素
删除单个元素有两种方法:
(1)mp.erase(it),it为迭代器,O(1)
(2)mp.erase(key),key为键,O(logN),N为map内元素的个数
#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
map<char,int> mp;
int main(){
mp['a']=1;
mp['b']=2;
mp['c']=3;
mp['d']=4;
map<char,int>::iterator it;
it=mp.find('c');
mp.erase(it);
mp.erase('d');
for(it=mp.begin();it!=mp.end();it++)
cout<<it->first<<" "<<it->second<<endl;
}
删除一个区间内所有元素
mp.erase(first,last).时间复杂度O(last-first).
#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
map<char,int> mp;
int main(){
mp['a']=1;
mp['b']=2;
mp['c']=3;
mp['d']=4;
map<char,int>::iterator it;
it=mp.find('b');
mp.erase(it,mp.end());
for(it=mp.begin();it!=mp.end();it++)
cout<<it->first<<" "<<it->second<<endl;
}
size()
获得map中映射的对数,O(1)
clear()
清空所有元素,复杂度O(N),N为map中元素的个数