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

前端 未结 7 1134
孤独总比滥情好
孤独总比滥情好 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:13

    If you try to access a key value using index operator [], then 2 things can happen :

    1. The map contains this key. So it will return the corresponding key value.
    2. The map doesn't contain the key. In this case, it will automatically add a key to the map with null value.

    "pootoo" key does't exist in your map. So it will automatically add this key with value = ""(empty string). And your program will print empty string.

    Here map size will increase by 1.

    To search a key you can use map_name.find(), which will return map_name.end() if the key doesn't exist. And no extra key will be added.

    You can use [] operator when you want to set value for a key.

提交回复
热议问题