c++ - c++ 使用自动引用进行迭代
问题描述
尽管在这里阅读了一堆帖子,但我仍然经常auto&
在 for (auto& x : some_container)
. 通常,为了避免为字符串类型构建临时副本并加快 for 循环迭代,我将auto&
其用作默认选项。
有人可以指导我何时以及如何正确使用auto&
吗?
编辑:
下面可能是一个不好的例子。我知道我们应该避免使用有效 C++ 书中的向量。但是,这个问题还要求提供使用自动和迭代容器的一般准则
今天,我又陷入了使用的另一个错误陷阱auto&
#include <vector>
#include <iostream>
using namespace std;
int main() {
int n = 3;
vector<bool> vec(n, false);
for(auto& x : vec) cout << x << " ";
cout << endl;
return 0;
}
错误信息如下所示。这是什么意思?
vector_bool.cpp:9:15: error: non-const lvalue reference to type '__bit_reference<[2 * ...]>' cannot bind to
a temporary of type '__bit_reference<[2 * ...]>'
for(auto& x : vec) cout << x << " ";
^ ~
解决方案
推荐阅读
- visual-studio - ASP.NET Core 项目上的 Winform 设计器问题
- android - WallpaperService - 引擎 - 区分系统和锁屏
- android - Android Q - 前台服务需要后台位置权限?
- java - 如何使用 Spring Data MongoDB 查询中的投影仅返回数组中匹配的对象?
- java - 在 lambda 中抛出异常不起作用
- python - 网页抓取 - 将文件保存到嵌套文件夹
- scala - 从 Kafka 主题读取处理数据并使用 scala 和 spark 写回 Kafka 主题
- django - 在管理员的 __str__ 方法中显示缩略图
- python - Google Dataproc Presto:如何使用 Python 运行查询
- go - 在 GUI 中从 for 循环中分配适当的值