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

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

本文关键字:STL 引用 元素 获取 for C++11 范围 循环      更新时间:2023-10-16
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,对这种混乱感到抱歉。

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