stl map下標引用元素的副作用

lt發表於2017-01-30

如果元素不存在,下標引用不會丟擲異常,而是建立一個此下標的元素,整數預設值是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

相關文章