#include<bits/stdc++.h>//#include using namespace std; int main(){ map<char,int> m;//尖括号里的两个数据类型可以是任何类型 //方法一:利用下标方式插入数据到map里 m['a']=100;//键 'a' ----值 100 m['b']=200; m['z']=300; m['k']=50; m['k']=90;//在键重复情况下,会覆盖(替换)值 //方法二:利用insert函数插入(注意:不会覆盖值) m.insert(pair<char,int>('x',500)); //利用pair对象 m.insert(map<char,int>::value_type('y',800));//使用value_type m.insert(map<char,int>::value_type('y',450));//使用value_type,没有覆盖,还是800

int v1=m['a'];//访问key是'a'的元素,如果不存在,会自动增加这个键值对,值是默认初始值
cout<<v1<<endl; //100

map<char,int>::iterator it1=m.find('b');//查找key是‘b’,返回迭代器,指向目标键值对
cout<<it1->first<<" "<<it1->second<<endl;//b 200

map<char,int>::iterator it2=m.find('w');
if(it2==m.end()){ //在find函数找不到目标时,返回值等于end()
	cout<<"没有找到w"<<endl; 
}else{
	cout<<"找到w"<<endl; 
}

cout<<"键值对的个数:"<<m.size()<<endl;
if(m.empty()){
	cout<<"为空"<<endl; 
}else{
	cout<<"不为空"<<endl;
}

int n=m.erase('z');//删除z这个键的键值对
cout<<n<<endl; //erase返回值是1代表删除成功,如果是0代表删除失败 
m.erase(it1);//it1是前面代码中查找关键字b的返回值(迭代器)

//m.erase(++m.begin(),--m.end());//删除除了开头和结尾以外的所有键值对
map<char,int>::iterator it3=m.begin();
it3++;
it3++;  //注意:迭代器不能做除了++和--以外的任何其他操作 
map<char,int>::iterator it4=m.end();
it4--;
it4--;
m.erase(it3,it4);//范围删除,保留前两个和后两个元素,删除范围包含起点不包含终点

m.clear();//清空map 

//遍历map,使用迭代器(iterator,本质是一个指针)
//begin()函数得到第一个键值对的地址,end()函数获得最后一个键值对的下一个位置的地址 
// 迭代器(iterator)类型的变量只能做两种操作,++和--,不能做任何其他操作
//++就是迭代器指向下一个键值对的地址,--就是迭代器指向上一个键值对的地址 
for(map<char,int>::iterator it=m.begin();it!=m.end();it++){
	cout<<it->first<<" "<<it->second<<endl;
	//it->first是这个指针指向的键值对数据里的键
	//it->second是这个指针指向的键值对数据里的值		 
} 
return 0;

} /* 1221001-map用法演示.cpp map:映射,存储一对一的数据。 map属于STL里的一个关联容器,描述数据之间的关联关系。 map提供一对一的数据处理,采用key-value(键值对)形式。 map里数据,默认按照键(key)升序排列

*/

1 条评论

  • 1