c++ map索引不存在的key可能導致的後果分析
阿新 • • 發佈:2020-12-15
今天調這個調了很久才發現這個問題,所以記錄以下
測試程式碼
#include<bits/stdc++.h> using namespace std; int main() { map<int,int>mp_int; map<string,string>mp_string; map<char,char>mp_char; mp_int[1]=10; string a="abc",b="xzy",c="def"; mp_string[a]=b; mp_char['a']='b'; cout<<"正常索引"<<endl; for(auto &i:mp_int)cout<<i.first<<" "<<i.second<<endl; for(auto &i:mp_string)cout<<i.first<<" "<<i.second<<endl; for(auto &i:mp_char)cout<<i.first<<" "<<i.second<<endl; cout<<"訪問不存在的鍵"<<endl; cout<<mp_int[2]<<endl<<mp_string[c]<<endl<<mp_char['c']<<endl; cout<<"變化"<<endl; for(auto &i:mp_int)cout<<i.first<<" "<<i.second<<endl; for(auto &i:mp_string)cout<<i.first<<" "<<i.second<<endl; for(auto &i:mp_char)cout<<i.first<<" "<<i.second<<endl; return 0; }
OUT PUT
正常索引
1 10
abc xzy
a b
訪問不存在的鍵
0
變化
1 10
2 0
abc xzy
def
a b
c
可以發現不存在的key在被索引後被新增到了map中並被賦予了一個預設值(一般的,整數為0,字元,字串為空)
需要注意的是,只要發生了索引,就會導致如上錯誤,即使他們在if語句裡
#include<bits/stdc++.h> using namespace std; int main() { map<int,c="def"; mp_string[a]=b; mp_char['a']='b'; cout<<"正常索引"<<endl; for(auto &i:mp_int)cout<<i.first<<" "<<i.second<<endl; for(auto &i:mp_string)cout<<i.first<<" "<<i.second<<endl; for(auto &i:mp_char)cout<<i.first<<" "<<i.second<<endl; cout<<"訪問不存在的鍵"<<endl; if(mp_int[2]); if(mp_string[c]==a); if(mp_char['c']); cout<<"變化"<<endl; for(auto &i:mp_int)cout<<i.first<<" "<<i.second<<endl; for(auto &i:mp_string)cout<<i.first<<" "<<i.second<<endl; for(auto &i:mp_char)cout<<i.first<<" "<<i.second<<endl; return 0; }
上面的程式碼會產生同樣的結果
當你想要再次使用(迴圈)這些鍵的時候就會出錯,你會使用到實際並不存在的key
避免方法是在索引前使用find或者count來判斷鍵是否存在
到此這篇關於c++ map索引不存在的key可能導致的後果分析的文章就介紹到這了,更多相關c++ map索引內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!