在基于 C++11 范围的'for'循环中获取对 STL 容器元素的引用
Acquiring the reference to an element of an STL container in a C++11 range-based 'for' loop
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 引用或副本。
相关文章:
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 如何重载下标运算符 [] 以引用 2d STL 数组?
- 如何通过引用对用户定义对象的类型集 (STL) 的数组元素进行增强迭代?
- STL算法函数,如累加,如果传递给它们的函数接受引用,请避免复制
- 在C++中,是否可以引用像C++中的stl列表这样的数据结构部分
- 操纵对STL容器(例如向量)中元素的引用
- C++STL容器和引用
- STL表示隐含交叉引用的数据结构的方法
- 传递对STL向量中偏移位置的引用
- STL中使用引用计数的数据结构存在哪些行为异常
- 如何在C++中存储对 stl 容器元素的指针/迭代器引用
- C++STL矢量:引用Push_back
- STL如何用非线性数据结构实现反向迭代器去引用
- 获取迭代器正在引用的STL容器的指针
- C++ stl unordered_map实现,引用有效性
- c++:应对通过引用传递的 stl 容器
- 如何在结构数据结构中使用 map stl 并初始化映射,然后引用它
- 您可以使用 boost::reference_wrapper 将引用存储在 STL 容器中吗?
- 在基于 C++11 范围的'for'循环中获取对 STL 容器元素的引用
- C++ 将引用节点推送到 STL 列表