您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)c++ 中map索引不存在如何解決,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
測(cè)試代碼
#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<<"訪(fǎng)問(wèn)不存在的鍵"<<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
訪(fǎng)問(wèn)不存在的鍵
0
變化
1 10
2 0
abc xzy
def
a b
c
可以發(fā)現(xiàn)不存在的key在被索引后被添加到了map中并被賦予了一個(gè)默認(rèn)值(一般的,整數(shù)為0,字符,字符串為空)
需要注意的是,只要發(fā)生了索引,就會(huì)導(dǎo)致如上錯(cuò)誤,即使他們?cè)趇f語(yǔ)句里
#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<<"訪(fǎng)問(wèn)不存在的鍵"<<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; }
上面的代碼會(huì)產(chǎn)生同樣的結(jié)果
當(dāng)你想要再次使用(循環(huán))這些鍵的時(shí)候就會(huì)出錯(cuò),你會(huì)使用到實(shí)際并不存在的key
避免方法是在索引前使用find或者count來(lái)判斷鍵是否存在
看完上述內(nèi)容,你們對(duì)c++ 中map索引不存在如何解決有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。