首页 > 解决方案 > 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 << " ";
              ^ ~

标签: c++

解决方案


推荐阅读