C++ Algorithm 库 - any_of() 函数
描述
C++ 函数 std::algorithm::any_of() 如果 predicate 对 first 到 last 范围内的任何元素返回 true,则返回 true。如果范围为空,则也返回 true,否则返回 false。
声明
以下是 std::algorithm::any_of() 函数形式 std::algorithm 头的声明。
C++11
template <class InputIterator, class UnaryPredicate> bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);
参数
first − 将迭代器输入到序列中的初始位置。
last − 将迭代器输入到序列中的最终位置。
pred − 一个一元谓词函数,它接受一个元素并返回一个 bool。
返回值
如果谓词对范围内的任何元素返回 true,或者如果范围为空,则返回 true,否则返回 false。
异常
如果谓词或迭代器上的操作引发异常,则引发异常。
请注意,无效参数会导致未定义的行为。
时间复杂度
first 和 last 之间的距离呈线性关系。
示例
以下示例显示了 std::algorithm::any_of() 函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool is_odd(int n) {
return (n % 2 != 0);
}
int main(void) {
vector<int> v = {2, 4, 6, 8, 11};
bool result;
result = any_of(v.begin(), v.end(), is_odd);
if (result == true)
cout << "Vector contains at least one odd number." << endl;
v[4] = 10;
result = any_of(v.begin(), v.end(), is_odd);
if (result == false)
cout << "Vector contains all even number." << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Vector contains at least one odd number. Vector contains all even number.

