当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ std::all_of()用法及代码示例


C++函数在STL的<algorithm>库中定义。此函数可在整个数组元素范围内运行,并且可以节省时间运行循环以逐个检查每个元素。它检查每个元素上的给定属性,并在范围内的每个元素满足指定属性时返回true,否则返回false。句法:

template <class InputIterator, class UnaryPredicate>
bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);
first:Input iterators to the initial positions in a sequence.
last: Input iterators to the final positions in a sequence.
pred: An unary predicate function that accepts an element and returns a bool.

异常:如果谓词或迭代器上的操作抛出异常,则抛出异常。
例子:

// C++ code to demonstrate working of all_of() 
#include <vector> 
#include <algorithm> 
#include <iostream> 
int main() 
{ 
    std::vector<int> v(10, 2); 
      
    // illustrate all_of 
    if (std::all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; }))  
    { 
        std::cout << "All numbers are even\n"; 
    } 
  
}

输出:


All numbers are even
// C++ code to demonstrate working of all_of() 
#include<iostream> 
#include<algorithm> // for all_of() 
using namespace std; 
int main() 
{ 
    // Initializing array 
    int ar[6] =  {1, 2, 3, 4, 5, -6}; 
  
    // Checking if all elements are positive 
    all_of(ar, ar+6, [](int x) { return x>0; })? 
          cout << "All are positive elements" :
          cout << "All are not positive elements"; 
  
    return 0; 
  
}

输出:

All are not positive elements

在上面的代码中,-6为负元素会否定条件并返回false。

有用的数组算法STL函数



相关用法


注:本文由纯净天空筛选整理自 std::all_of() in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。