Acquiring a reference to an STL container element in a for loop in C ++ 11

for (Something something : setOfSomething)          // OK
for (Something const& something : setOfSomething)   // OK
for (Something& something : setOfSomething)         // ERROR

error: invalid initialization of reference of type 'Something&'
from expression of type 'const Something'

Since when does the iterator return const Something? It must return either Something&or Something const&. And since the range-based "for" loop is interpreted as which , I have no plausible explanation of what is happening.

Edit: I'm talking about unordered_set, not set, sorry for this confusion.

+5
source share
1 answer

You cannot mutate elements set, as this can violate invariants set. Thus, the compiler limits you to returning links or copies of const.

+13
source

All Articles