5
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'

从什么时候迭代器返回const Something?它应该返回Something&Something const&。而且由于基于范围的“for”循环被解释为这样我对正在发生的事情没有合理的解释。

编辑:我说的是,unordered_set而不是set,对这种混乱感到抱歉。

4

1 回答 1

13

您不能改变 a 的成员,set因为这可能违反set不变量。所以编译器限制你获取 const 引用或复制回来。

于 2012-04-17T16:05:08.323 回答