📜  C++ STL-algorithm.all_of()函数

📅  最后修改于: 2020-10-16 09:14:19             🧑  作者: Mango

C++ STL algorithm函数all_of()

如果’pred’参数的值为true,则C++ STL algorithm.all_of()函数将返回true值。对于[first,last]范围内的所有元素,该值均应为true。

句法

template 
bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);

参数

first:它指定列表中的第一个元素。

last:它指定列表中的最后一个元素。

pred:这是一个一元函数,它接受范围内的参数。

返回值

该函数具有一种返回类型“ true”。如果参数’pred’的值对于范围中的所有元素都是true,则返回值’true’,否则返回false。

例子1

#include
#include
#include
int main()
{
    std::array arr= {25,27,29,31,33,35};
    if ( std::all_of(arr.begin(), arr.end(), [](int k) {return k%2;} ) )
    std::cout <<"All the array elements are odd.";
    return 0;
}

输出:

All the array elements are odd.

例子2

#include
#include
using namespace std;
int main()
{
    int ar[6] = {2, 5, -7, -9, 3, 5};
    all_of(ar, ar+6, [](int x) { return x>0; })?
    cout<<"All elements are positive \n":
    cout<<"All elements are not positive";
    return 0;
}

输出:

All elements are not positive 

复杂度

函数从第一个元素开始向最后一个元素线性移动。对于列表中的每个元素,都会检查“ pred”的值。搜索继续进行,直到遇到“ pred”值不匹配的情况。

数据竞争

该函数访问指定范围内的所有对象或其中的一些对象。

异常处理

如果任何参数抛出一个异常,该函数将引发异常。