在C++ 11基于范围的'for'循环中获取对STL容器元素的引用

Ale*_*aev 5 c++ iterator for-loop stl reference

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'
Run Code Online (Sandbox Code Playgroud)

迭代器何时返回const Something?它应该返回Something&Something const&.而且,由于基于范围的for循环这样解释的是,我有什么事情没有合理的解释.

编辑:我正在谈论unordered_set而不是set抱歉这种混乱.

Mar*_*k B 13

你不能改变a的成员,set因为这可能会违反set不变量.因此编译器会限制您获取const引用或副本.

  • @Haroogan:不再了.我认为它在C++ 03中做过,但委员会准确地修复了它.如果你事先知道某些成员没有破坏`set`的不变量,那么将它声明为`mutable`并提供一个`const`访问器. (4认同)