【发布时间】:2020-08-06 07:47:19
【问题描述】:
我是新手,正在学习如何以更灵活的方式使用 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);这一行声明了一个向量并分配了空间。
我的疑问是:
-
我对
(auto &it : a) cin >> it;的这个工作原理感到困惑。 -
ok &= (a[i] - a[i - 1] <= 1);这个表达我也看不懂。
【问题讨论】:
-
这是一个基于范围的 for 循环:en.cppreference.com/w/cpp/language/range-for
-
阅读a good C++ book可以更好地回答这类问题
标签: c++ for-loop vector operators