+ 1

issue with map and [] operator

Hi Refer code below: https://www.sololearn.com/en/compiler-playground/cu5ZgEHv7zkm It is an obvious that map[key] adds new element to map with {key, default value} to map if key is not found. Due to this, cannot use const map ref. Even though I type casted to get rid off the constant, it compiles but still modifies map as expected. To avoid modification was main purpose to use const map ref in a function. To achieve this, I created a test2 method instead of test method. Is there a better way to obtain result apart from test2 method or map.find?

19th Sep 2024, 7:46 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Respuestas
+ 4
<std::map> doesn't have a const version of <operator[]>, try <std::map::at>.
19th Sep 2024, 9:51 AM
MO ELomari
MO ELomari - avatar
0
Thanks
19th Sep 2024, 10:23 AM
Ketan Lalcheta
Ketan Lalcheta - avatar