0
Const key of map
Hi As we know, map key cannot be updated. So , we should get key of map as const ref. Why this code works ? It should not yhrow error as auto is not automatically const. Should for loop must not be as below ? for(const auto& [key,val] : mp) I know val is not const , but somehow should notify that key is const. How to do this if it was not map and was vector of my user defined pair where I want key const. https://sololearn.com/compiler-playground/cx24PDRJdDIm/?ref=app
2 Respuestas
+ 3
it's just reading, there's no modification happening here.
in range-based for loop, using const auto& is a good practice to indicate that it is doing a read only operation.
but it's not mandatory. just good practice.
using only auto& is also valid and allowed, as long as you don't modify the map's key when iterating.
you can see that in your example if you uncomment the key+=1. then the error is raised.
I'm not sure i quite understand the vector<pair> part, though.
perhaps you mean something like this?
https://sololearn.com/compiler-playground/cx89P47q79U5/?ref=app
0
It is correct. Why there is no provision to mark key as const in for loop. It becomes easy to understand that key is const in vector of pair just by looking at for loop.
Something like below happens
for(const int a : num) meaning elements are const of num vector. We don't need to go to definition of num to check whether element is non modifiable or not.
Same thing is not available with [] notation?