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引用或副本.