#include<bits/stdc++.h>
using namespace std;
void show(map<int,string>& mp)
{
map<int,string>::iterator iter=mp.begin();
while(iter!=mp.end())
{
cout<<iter->first<<" "<<iter->second<<endl;
iter++;
}
cout<<endl;
}
int main()
{
//构造 map
map<int,string> mp;
mp.insert({5,"map 5"});//使用{}
mp.insert({6,"map 6"});//使用{}
mp.insert({7,"map 7"});//使用{}
mp.insert({8,"map 8"});//使用{}
mp.insert({0,"map 0"});//使用{}
mp.insert({1,"map 1"});//使用{}
mp.insert({2,"map 2"});//使用{}
mp.insert({3,"map 3"});//使用{}
mp.insert({4,"map 4"});//使用{}
//查找数据和修改数据
//由key查找value时,首先要判断map中是否包含key。
//map提供了两种方式,查看是否包含key,m.count(key),m.find(key)。
//m.count(key):由于map不包含重复的key,因此m.count(key)取值为0,或者1,表示是否包含。
//m.find(key):返回迭代器,判断是否存在。
//1:count()
if(mp.count(1)>0){
cout<<1<<" 查到了"<<endl;
mp[1]="100";//1:可直接修改
cout<<" 修改为"<<mp[1]<<endl;
}else{
cout<<"没查到"<<endl;
}
//2:find() 推荐这一种,因为count需要查两次;也有find(begin,end,target)查找目标
map<int,string>::iterator iter=mp.find(2);
if(iter!=mp.end()){
cout<<iter->first<<" 查到了"<<endl;
(*iter).second="2000";//2:迭代器修改
cout<<" 修改为"<<mp[2]<<endl;
iter->second="1000";//2:迭代器修改
cout<<" 修改为"<<mp[2]<<endl;
}
else {
cout<<"没查到"<<endl;
}
return 0;
}