如果元素不存在,下标引用不会抛出异常,而是创建一个此下标的元素,整数默认值是0.

#include <cstdio>
#include <map>
std::map<int,int> ma,mb,mc;
int main()
{
    ma[0]=1;
    ma[4]=1;
    printf("%d\n",ma.size());
    for(int i=0; i<5; i++)
        if(ma.find(i)!= ma.end())
            printf("%d\n",i);
    printf("%d\n",ma.size());

    printf("-----------\n");
    mb[0]=1;
    mb[4]=1;
    printf("%d\n",ma.size());
    for(int i=0; i<5; i++)
        if(mb[i]== 1)
            printf("%d\n",i);
    printf("%d\n",mb.size());

    printf("-----------\n");
    mc[0]=1;
    mc[4]=1;
    printf("%d\n",ma.size());
    for(int i=0; i<5; i++)
        printf("%d\n",mc[i]);
    printf("%d\n",mc.size());
}

运行结果

-----------
2
0
4
2
-----------
2
0
4
5
-----------
2
1
0
0
0
1
5