What happens if I read a map's value where the key does not exist?

前端 未结 7 1136
孤独总比滥情好
孤独总比滥情好 2020-12-05 12:24
map dada;
dada[\"dummy\"] = \"papy\";
cout << dada[\"pootoo\"];

I\'m puzzled because I don\'t know if it\'s considered

7条回答
  •  我在风中等你
    2020-12-05 13:09

    If operator [] doesn't find a value for the provided key, it inserts one at that position.

    But you should note that if you visit a not exist key and invoke it's member function, like mapKV[not_exist_key].member_fun().The program may crash.

    Let me give an example, test class as below:

    struct MapValue{
        int val;
    
        MapValue(int i=0){
            cout<<"ctor: "<

    Test code:

    cout<<"-------create map-------"< idName{{1, MapValue(1)}, {2, MapValue(2)}};
    
    cout<<"-----cout key[2]-----"<

    Output as below:

    -------create map-------
    ctor: 1
    ctor: 2
    dtor: 2
    dtor: 1
    dtor: 2
    dtor: 1
    -----cout key[2]-----
    MapValue: 2
    
    -----cout key[5]-----
    ctor: 0
    MapValue: 0
    
    -------runs here means, does't crash-------
    dtor: 0
    dtor: 2
    dtor: 1
    

    We can see that: idName[5] invoke map construct {5, MapValue(0)} to insert to idName.

    But if, you invoke member function by idName[5], then the program crashes :

    cout<<"-------create map-------"< idName{{1, MapValue(1)}, {2, MapValue(2)}};
    
    
    idName[5].toString();  // get crash here.
    
    
    cout<<"------- runs here means, doesn't crash-------"<

提交回复
热议问题