#include
using namespace std;
//map定义
map<typename1,typename2>mp;//映射前类型(键key),映射后类型(值value)
//字符串映射整数数组
map<string,int>mp;
//将set容器映射到一个字符串
map<set<int>,string>mp;
1、通过下标访问
例如:
map
mp[‘c’]=20;
#include
#include
using namespace std;
int main(){
map<char,int>mp;
mp['c']=20;
mp['c']=30;//20被覆盖
printf("%d\n",mp['c']);//输出30
return 0;
}
2、通过迭代器访问
//通过迭代器定义与其他STL容器迭代器定义方式相同
map<typename1,typename2>::iterator it;
通过it同时访问键和值
map可以用it->first访问键,用it->second访问值
#include
#include
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;
}
//find(key)返回键为key的映射迭代器,时间复杂度为O(logN),N为map中映射的个数
#include
#include
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;
}
1)、删除单个元素
map.erase(it),it为需要删除元素的迭代器,时间复杂度为O(1)
#include
#include
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;
}
map.erase(key),key为欲删除映射的键,时间复杂度 为O(logN),N为map内元素的个数
#include
#include
using namespace std;
int main(){
map<char,int>mp;
mp['a']=1;
mp['b']=2;
mp['c']=3;
mp.erase('b');//删除键为b的映射,即b 2
for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
printf("%c %d\n",it->first,it->second);
}
return 0;
}
2)、删除一个区间内所有元素
mp.erase(first,last),first为需要删除的区间起始迭代器,last为需要删除的区间的末尾迭代器的下一个地址,即删除左闭右开[first,last),时间复杂度为O(last-first)
#include
#include
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()); //删除it之后的左右映射,即b 2,c 3
for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
printf("%c %d\n",it->first,it->second);
}
return 0;
}
#include
#include
using namespace std;
int main(){
map<char,int>mp;
mp['a']=10;
mp['b']=20;
mp['c']=30;
printf("%d\n",mp.size());//3对映射
return 0;
}
#include
#include
using namespace std;
int main(){
map<char,int>mp;
mp['a']=1;
mp['b']=2;
mp['c']=3;
mp.clear(); //清空map
printf("%d\n",mp.size());
return 0;
}