版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ma2595162349/article/details/87815837
当用访问map存在的下标时,大家都指的答案。当访问不存在的下标时,又会发生什么呢?来看下
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<int,string> m;
m[2] = "good";
cout << m[2] << endl;
cout << m[3] << endl;
if(m.find(3) != m.end())
{
cout << "has m[3]"<< endl;
}
map<int,int> m1;
m1[2] = 10;
cout << m1[2] << endl;
cout << m1[3] << endl;
return 0;
}
打印:
good
has m[3]
10
0
由打印的结果可知,当访问一个map不存在的下标时,便会产生新的key。string类型打印的值是空,int类型打印的值是0。