for(auto &it: a) 是什么意思?

What does for(auto &it: a) mean?

我是新手,正在学习如何更灵活地使用c++语言。

在一个竞赛题中我看到有人写这样的代码:

#include <bits/stdc++.h>
using namespace std;

int main() {
#ifdef _DEBUG
    freopen("input.txt", "r", stdin);
//  freopen("output.txt", "w", stdout);
#endif
    
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<int> a(n);
        for (auto &it : a) cin >> it;
        sort(a.begin(), a.end());
        bool ok = true;
        for (int i = 1; i < n; ++i) {
            ok &= (a[i] - a[i - 1] <= 1);
        }
        if (ok) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

我假设这一行 vector<int> a(n); 声明了一个向量并分配了 space。

我的疑惑是:

  1. 我对 (auto &it : a) cin >> it; 的工作原理感到困惑。

  2. 我也不明白ok &= (a[i] - a[i - 1] <= 1);.

    这个表达

语法:

for (auto& it : a)

称为 range-based 循环。

它用于操作a数组或向量中给定的每个元素,元素的类型将等同于a的类型。

OTOH,& 声明对 a 中的任何元素 it 进行的任何修改都将被最初替换,并且不会为临时使用而制作副本(即通过引用).

简而言之,如果一个元素的值为 3,如果将其更改为 5,则原始数组或向量将受到影响。


ok &= (a[i] - a[i - 1] <= 1);

等价于 isn't a reference to operator,在这种情况下它是按位的:

ok = ok & (a[i] - a[i - 1] <= 1);

由于ok的类型是bool,所以只能持有true (1)false (0)

你有一个 vector<T> x 然后你想遍历每个元素

你可以用旧的“c”风格做这样的事情:

for (int i=0; i<x.size(); ++i)

但您也可以使用 range-based 循环执行以下操作:

for (T i:x)

结果是 i 是从向量中的元素获取的副本 因此,如果您需要的是您所做的参考:

for (T& i:x)

这里是你的代码的答案,因为 c++11 你可以自动推断出 i auto 的类型 因此语法

for (auto& i : x)

1.

(auto &it : a) cin >> it 

表示您采用向量 a.

的输入

类似于:

for(int i = 0 ; i < n; i++){
    cin>>a[i]; 
}

auto 关键字指定正在声明的变量的类型将自动从其初始值设定项中扣除。所以这里 it 引用 a[i] 并代替 a[i] 作为 it.

工作

2.

(a[i] - a[i - 1] <= 1)

结果布尔值 1(如果条件为真)或 0(如果条件为假)。

ok &= (a[i] - a[i - 1] <= 1) 

表示ok = ok & 1ok = ok & 0,取决于条件真假。