无涯教程-C++ 算法 - any_of函数

53 阅读1分钟

C++算法any_of()函数对参数中的每个元素测试pred的值,如果对于任何元素pred的值为true,则该函数返回true,否则返回false。

any_of - 语法

template <class InputIteratir, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);

any_of - 参数

first  - 它是指定参数内的第一个元素。

last   - 它是参数中的最后一个元素。

pred  - 这是一元函数,可以接受参数内的参数。

any_of - 返回值

该函数具有一种返回类型" true"。如果参数pred的值对于该参数的任何元素为true,则返回值true,否则返回false。

any_of - 例子1

#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
	int arr[7] = {2,4,6,5,10,3,14};
	any_of(arr,arr+6, [](int k){return k%2;})?
	cout <<"There are elements which exist in the table of 2":
	cout<<"No elements in the table of 2 exists";
	return 0;
}

输出:

There are elements which exist in the table of 2.

any_of - 例子2

#include <iostream>
#include <algorithm>
#include <array>
int main()
{
	std::array<int, 5> arr = {2,-4,6,-9,10};
	if(std::any_of (arr.begin(), arr.end(), [](int k) { return k<0;}))
	std::cout <<"Negative elements exist in the array";
	return 0;
}

输出:

Negative elements exist in the array

参考链接

www.learnfk.com/c++/cpp-alg…