C++ any_of()
C++ 算法函数any_of()
C++ 算法any_of()函数对范围内的每个元素测试" pred"的值,如果对于任何元素,pred的值为true,则函数返回true,否则返回false。
语法
template <class InputIteratir, class UnaryPredicate>
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);
参数
first: 它是指定范围内的第一个元素。
last : 这是范围中的last元素。
pred : 这是一元函数,可以接受范围中的参数。
返回值
该函数具有一个返回类型'true'。如果参数'pred'的值对于该范围的任何元素为true,则返回值'true',否则为false。
示例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.
示例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
复杂度
该函数从第一个元素开始向last元素线性移动。对于列表中的每个元素,都会检查" pred"的值。搜索继续进行,直到遇到与" pred"值不匹配的地方。
数据竞争
该函数将访问指定范围内的所有对象或某些对象
异常
如果任何参数抛出一个异常,该函数就会引发异常。