• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Niro Einteson
文可提笔安天下 武可上马定乾坤
博客园    首页    新随笔    联系   管理    订阅  订阅

map查找并修改元素

map查找并修改元素

 

测试代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 void show(map<int,string>& mp)
 4 {
 5     map<int,string>::iterator iter=mp.begin();
 6     while(iter!=mp.end())
 7     {
 8         cout<<iter->first<<" "<<iter->second<<endl;
 9         iter++;
10     }
11     cout<<endl;
12 }
13 int main()
14 {
15     //构造 map
16     map<int,string> mp;
17     mp.insert({5,"map 5"});//使用{}
18     mp.insert({6,"map 6"});//使用{}
19     mp.insert({7,"map 7"});//使用{}
20     mp.insert({8,"map 8"});//使用{}
21     mp.insert({0,"map 0"});//使用{}
22     mp.insert({1,"map 1"});//使用{}
23     mp.insert({2,"map 2"});//使用{}
24     mp.insert({3,"map 3"});//使用{}
25     mp.insert({4,"map 4"});//使用{}
26 
27     //查找数据和修改数据
28     //由key查找value时,首先要判断map中是否包含key。
29     //map提供了两种方式,查看是否包含key,m.count(key),m.find(key)。
30     //m.count(key):由于map不包含重复的key,因此m.count(key)取值为0,或者1,表示是否包含。
31     //m.find(key):返回迭代器,判断是否存在。
32     //1:count()
33     if(mp.count(1)>0){
34         cout<<1<<" 查到了"<<endl;
35         mp[1]="100";//1:可直接修改
36         cout<<" 修改为"<<mp[1]<<endl;
37     }else{
38         cout<<"没查到"<<endl;
39     }
40     //2:find() 推荐这一种,因为count需要查两次;也有find(begin,end,target)查找目标
41     map<int,string>::iterator iter=mp.find(2);
42     if(iter!=mp.end()){
43         cout<<iter->first<<" 查到了"<<endl;
44        (*iter).second="2000";//2:迭代器修改
45         cout<<" 修改为"<<mp[2]<<endl;
46         iter->second="1000";//2:迭代器修改
47         cout<<" 修改为"<<mp[2]<<endl;
48     }
49     else {
50         cout<<"没查到"<<endl;
51     }
52 
53     return 0;
54 }

 

运行结果:

1 1 查到了
2  修改为100
3 2 查到了
4  修改为2000
5  修改为1000

 

 

posted @ 2019-12-01 20:55  Nirogo  阅读(2451)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3