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。
相關用法
注:本文由純淨天空篩選整理自 std::all_of() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。