In this article we will discuss std::all_of() STL Algorithm, which is introduced in c++11.

Need of std::all_of()

This STL algorithm is useful when you have a range/array of element and you want to check if all elements in given range satisfies a given condition. It’s just opposite to std::any_of().

std::all_of() Introduction

all_of() accepts a range of elements and a Unary Predicate (i.e a call back) as an argument.

all_of() iterates over all the elements in given range and for each elements calls the given callback i.e. Unary Predicate.
If for any element then given predicate returns false then it stops the further iteration and return false, else it returns true.

std::all_of() usage details

How to use std::all_of() with two different type of callbacks i.e Lambda Function and Function pointer.

Using std::all_of() with Lambda Function

Suppose We have a vector of strings i.e.

Now we want to check if all strings in vector are of same size i.e. 4 using std::all_of(),

std::all_of() will iterate through all the strings in vector and for each string in vector it calls the passed lambda function, that checks if size of string is 4. If for any string the lambda function returns false, std::all_of() will stop the further iteration and returns false else it returns true.

Now Check if all strings in vector starts with a Upper Case Letter using all_of(),

Using std::all_of() with a Function Pointer

Suppose we have a string i.e.

Now let’s Check if given string contains all lower case letters i.e. not a single upper case char

Using std::all_of() with Arrays

Suppose we have an array i.e.

Now we will check if all numbers in array are multiple of 3 using all_of() i.e.

So, basically std::all_of() is to make our life easy.

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.