C++ <algorithm> - all_of() Function
The C++ algorithm::all_of function returns true if pred returns true for all elements in the range [first,last) or if the range is empty, else returns false.
Syntax
template <class InputIterator, class UnaryPredicate> bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);
Parameters
first |
Specify initial position of the input iterator. The range used is [first,last). |
last |
Specify final position of the input iterator. The range used is [first,last). |
pred |
Specify an unary function that accepts an element in the range as argument, and returns a value convertible to bool. The function returns true if the element satisfy the given condition. |
Return Value
Returns true if pred returns true for all elements in the range or if the range is empty, else returns false.
Time Complexity
Up to Linear i.e, Θ(n).
Example:
In the example below, the algorithm::all_of function is used to check whether all elements of a given sequence satisfy the specified condition or not.
#include <iostream> #include <algorithm> #include <vector> using namespace std; bool isPositive (int i) { return (i > 0) ; } int main (){ int arr[] = {10, 15, 12, -15, 14, -12}; vector<int> vec = {10, 15, 12, 15, 14, 12}; //check if all elements in the array are positive bool b1 = all_of(arr, arr+6, isPositive); //check if all elements in the vector are positive bool b2 = all_of(vec.begin(), vec.end(), isPositive); //print result for array if(b1) { cout<<"All elements of array are positive.\n"; } else { cout<<"All elements of array are not positive.\n"; } //print result for vector if(b2) { cout<<"All elements of vector are positive.\n"; } else { cout<<"All elements of vector are not positive.\n"; } return 0; }
The output of the above code will be:
All elements of array are not positive. All elements of vector are positive.
❮ C++ <algorithm> Library