简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM