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

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM