How to use the all_of() function in C++

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.

Parameters

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 satisfiedreturns true or notreturns false.

Return

The all_of() function returns a Boolean value true if all the elements in the range satisfied the condition; otherwise, it returns false.

Code

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.";
else
cout << "All the elements are not odd numbers.";
return 0;
}

Explanation

  • From lines 1 to 3, we import the required header files.
  • In line 6, we create our unary function that will return true if the number is odd; otherwise, it will return false.
  • In line 11, we create a vector of integers.
  • In line 13, we call the all_of() function and pass the required parameters.
  • Then, in line 14, we print if all the elements are odd. Otherwise, we print in line 16 that all the elements are not odd numbers.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources