The all_of()
function in C++ helps to determine if all the elements in the specified range satisfy the condition or not. This function is available in the <algorithm.h>
header file.
The all_of()
function accepts the following parameters:
first
: This is an iterator that points to the start index of the array or vector where we want to perform this check.
last
: This is an iterator that points to the last index of the array or vector where we want to perform this check.
condition
: This is a unary function that accepts one element of the same type as you have elements in the array or vector. This unary function returns a Boolean value that indicates whether the condition is
The all_of()
function returns a Boolean value true
if all the elements in the range satisfied the condition; otherwise, it returns false
.
Let’s have a look at the code now.
#include <iostream>#include <vector>#include <algorithm>using namespace std;bool AreAllOdd(int i){return (i % 2 == 1);}int main() {vector<int> vec = {3,5,7,11,13,17,19,23};if (all_of(vec.begin(), vec.end(), AreAllOdd))cout << "All the elements are odd numbers.";elsecout << "All the elements are not odd numbers.";return 0;}
true
if the number is odd; otherwise, it will return false
.all_of()
function and pass the required parameters.