std::any_of 是 C++ 标准库中的一个算法,用于判断给定范围内的元素是否至少有一个满足指定的条件。
语法
template< class InputIt, class UnaryPredicate >
bool any_of( InputIt first, InputIt last, UnaryPredicate p );
first 和 last:定义了要搜索的元素范围的迭代器对(iterator pair)。[first, last) 表示范围,即从 first 开始(包括 first),到 last 结束(不包括 last)。
p:是一个谓词(predicate)函数或可调用对象,用于定义搜索的条件。谓词应该是一个可接受范围内元素类型的函数,返回 bool 类型。
#include <algorithm>
#include <iostream>
#include <vector>
//std::all_of 用于检查容器中的所有元素是否都满足指定的条件。
//std::none_of 用于检查容器中的所有元素是否都不满足指定的条件。
//std::find 用于在容器中查找第一个满足指定条件的元素。
void test01()
{
std::vector<int> numbers = { 1, 2, 3, 4, 5 };
// 使用 std::any_of 判断是否存在偶数
bool hasEven = std::any_of(numbers.begin(), numbers.end(), [](int x) {
return x % 2 == 0;
});
if (hasEven) {
std::cout << "数组中存在偶数。\n";
}
else {
std::cout << "数组中不存在偶数。\n";
}
}
void test02()
{
std::vector<int> numbers = { 1, 2, 3, 4, 5 };
// 使用 std::any_of 判断是否存在偶数
bool hasEven = std::any_of(numbers.begin(), numbers.end(), [](int x) {
return x % 2 == 0;
});
if (hasEven) {
std::cout << "数组中存在偶数。\n";
}
else {
std::cout << "数组中不存在偶数。\n";
}
}
// std::any_of 是 C++ 标准库 <algorithm> 头文件中的一个算法,用于检查给定范围内的元素是否满足指定的条件。
int main() {
test01();
return 0;
}