Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acquiring the reference to an element of an STL container in a C++11 range-based 'for' loop

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 iterator return const Something? It should return either Something& or Something const&. And since range-based 'for' loop is interpreted like that, I have no plausible explanation for what's going on.

Edit: I'm talking about unordered_set rather than set, sorry about this confusion.

like image 995
Alexander Shukaev Avatar asked Apr 17 '12 16:04

Alexander Shukaev


1 Answers

You can't mutate the members of a set because that could violate the set invariants. So the compiler restricts you to getting const references or copies back out.

like image 79
Mark B Avatar answered Oct 03 '22 15:10

Mark B