当初c++学的很潦草,很多细节都不知道。
今天写程序时,偶然发现有的没加入map的key,在调用map.count(key)函数时返回的是1。
仔细的调程序后发现,这些特殊的key值,之前都被执行过这条语句。
string a = map[key];
后来反复试验,又查了资料,发现执行过这条语句的key(执行前不在map中),会被加入到map中,对应的值是空值。
int main(){
map<int,string> mapp;
mapp[1] ="a";
mapp[3] ="b";
mapp[2] ="c";
cout<<"执行前"<<endl;
map<int,string>::iterator iter;
for(iter = mapp.begin(); iter !=mapp.end(); iter++) {
cout << iter->first << " : " << iter->second << endl;
}
string a = mapp[6];
cout<<"执行后"<<endl;
for(iter = mapp.begin(); iter !=mapp.end(); iter++) {
cout << iter->first << " : " << iter->second << endl;
}
}
如果值是int类型的,对应为0。
还有,map声明是最好不要声明成map,否则遍历时会报错。