c++ map索引不存在的key可能導(dǎo)致的后果分析
今天調(diào)這個(gè)調(diào)了很久才發(fā)現(xiàn)這個(gè)問題,所以記錄以下
測試代碼
#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
可以發(fā)現(xiàn)不存在的key在被索引后被添加到了map中并被賦予了一個(gè)默認(rèn)值(一般的,整數(shù)為0,字符,字符串為空)
需要注意的是,只要發(fā)生了索引,就會(huì)導(dǎo)致如上錯(cuò)誤,即使他們在if語句里
#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;
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來判斷鍵是否存在
到此這篇關(guān)于c++ map索引不存在的key可能導(dǎo)致的后果分析的文章就介紹到這了,更多相關(guān)c++ map索引內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C++ map用法總結(jié)(整理)
- C++保存HBITMAP為位圖文件的實(shí)現(xiàn)方法
- C++利用map實(shí)現(xiàn)并查集
- c++容器list、vector、map、set區(qū)別與用法詳解
- C++ map 根據(jù)value找key的實(shí)現(xiàn)
- C++中rapidjson將嵌套map轉(zhuǎn)為嵌套json的講解
- C++中rapidjson將map轉(zhuǎn)為json的方法
- C++中rapidjson組裝map和數(shù)組array的代碼示例
- C++中map和vector作形參時(shí)如何給定默認(rèn)參數(shù)?
- c++ 數(shù)據(jù)結(jié)構(gòu)map的使用詳解
相關(guān)文章
C++模擬實(shí)現(xiàn)STL容器vector的示例代碼
這篇文章主要為大家詳細(xì)介紹了C++如何模擬實(shí)現(xiàn)STL容器vector的相關(guān)資料,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C++有一定幫助,需要的可以參考一下2022-11-11

