map用法
map构造函数:
map<int/char/string(原变量),int/char/string(现变量)>mapint/char/string;
map添加数据:
map<int,string>mp;
1.mp.insert(pair<int,string>(233,"orzmxh"));
2.mp.insert(map<int,string>::value_type(521,"orzhzh"));
3.mp[666]="orzhhw";
mp->first第一项 mp->second第二项
map函数:
mp.begin() 返回首元素的迭代器指针
mp.end() 返回尾元素的迭代器指针
mp.size() 目前元素个数
mp.bool() 判断容器是否空,若返回true,表明容器已空
mp.find(key) 返回键值等于key的迭代器指针
mp.count(key) 返回键值等于key的元素的个数
mp.lower_bound(key) 返回键值大于等于key的迭代器指针
mp.upper_bound(key) 返回键值大于key的迭代器指针
mp.erase(key) 删除迭代指针key处元素
mp.erase(l,r) 删除[l,r)之间元素
mp.swap(mp2) 交换mp和mp2映射元素
mp.clear() 删除所有元素
#include<map>
#include<cstdio>
using namespace std;
map<char,int> mp1,mp2;
map<char,int>::iterator it;
int main(){
mp1['a']=1;mp1['b']=2;
mp1['c']=3;mp1['d']=4;
mp2.insert(pair<char,int>('e',10));
mp2.insert(pair<char,int>('f',40));
mp2.insert(map<char,int>::value_type('g',60));
mp2.insert(map<char,int>::value_type('h',80));
mp1.swap(mp2);
it=mp2.find('b');
printf("%d\n",it->second);//2
mp2.erase(mp2.find('b'),mp2.find('d'));//<a,1> <d,4>
printf("%d\n",mp2.size());//2
printf("%d\n",mp1.count('g'));//1
for(it=mp1.begin();it!=mp1.end();it++)//<e,10><f,40>
printf("%c %d\n",it->first,it->second);//<g,60><h,80>
}
评论 (0)