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

c++, for-loop, iterator, reference, stl

Solution

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.

Problem

``` 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.

Original source