在 ifcondition al中 find() C++ STL 中的 == a.end() 有什么用?

what is the use of == a.end() in find() c++ stl in if conditional?

本文关键字:end 什么 STL al ifcondition find C++ 中的      更新时间:2023-10-16

我刚刚解决了一个codeforce问题,我在作者的教程解决方案中发现了关于find(( c ++ stl的一些新东西......但我无法理解。在这里,find(a.begin(), a.end(), s-i) == a.end()==a.end()做什么?

(问题链接:http://codeforces.com/contest/1293/problem/A(

//Author's tutorial solution
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
#define endl 'n'
int n, s, k;
vector<int> a;
void Input() {
cin >> n >> s >> k; a.clear(); a.resize(k);
for (auto &z: a) cin >> z;
}
void Solve() {
for (int i=0; i<=k; i++) {
if (s-i >= 1 && find(a.begin(), a.end(), s-i) == a.end()) {cout << i << endl; return;} //SEE HERE
if (s+i <= n && find(a.begin(), a.end(), s+i) == a.end()) {cout << i << endl; return;} //SEE HERE
}
assert(false); 
int main(int argc, char* argv[]) {
ios_base::sync_with_stdio(0); cin.tie(NULL);
int T; cin >> T; while (T--) {Input(); Solve();} return 0;
}

std::find和其他类似函数将迭代器返回到找到的元素。如果在容器中找不到该元素,则返回的迭代器将指向指定范围的末尾(在本例中为std::end(。因此,find(a.begin(), a.end(), s-i) == a.end()意味着元素s-i不在容器a中。

CPP 参考

根据文档 (http://www.cplusplus.com/reference/algorithm/find/(:

返回:对比较范围中第一个元素的迭代器 等于瓦尔。如果没有匹配的元素,函数将返回最后。

find(a.begin(), a.end(), s-i)试图在a中找到s-i,并在失败时返回a.end()

find(a.begin(), a.end(), s-i) == a.end()是一个布尔表达式,当a中找不到s-i时,它的计算结果为true,否则false